1

I have a simple JSON string in my class.

String json = "{'key1':'value1','key2':'value2'}";

And I want create 3 simple methods that will

1. Put value in my JSON string.
2. Get value in my JSON string.
3. Remove value in my JSON string.

Is there any simple library in Java? Or I have to implement it myself?

Thanks!

Eazy
  • 3,212
  • 5
  • 24
  • 40

3 Answers3

3

Use Jackson:

http://wiki.fasterxml.com/JacksonInFiveMinutes

Serialization:

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValue(new Simple());

and with POJO like:

public class Simple {
    public int x = 1;
    public int y = 2;
}

you would get something like:

{"x":1, "y":2}

(except that by default output is not indented: you can enabled indentation using standard Jackson mechanisms)

Deserializing POJOs from JSON:

ObjectMapper mapper = new ObjectMapper();
Simple value = mapper
   .readValue("{\"x\": 1, \"y\": 2}", Simple.class);
Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
2

Gson can convert Java objects and JSON to each other.

reprogrammer
  • 14,298
  • 16
  • 57
  • 93
  • Yes Gson works well. There's also http://jackson.codehaus.org/ if Gson doesn't float your boat. – Programming Guy Dec 04 '12 at 04:08
  • If using GSON. I need to use MAP? String json = "{'data1':100,'data2':'hello'}"; Gson gson = new Gson(); Map obj = gson.fromJson(json, Map.class); – Eazy Dec 04 '12 at 04:08
  • If the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method. See http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html#fromJson(java.lang.String, java.lang.reflect.Type) – reprogrammer Dec 04 '12 at 04:21
  • Note that your example json string (above comment) does not correspond to a valid Java `Map` (with values of boxed primitive types) because the types of the values differ. If the types vary, you should read the json into a custom object rather than a `Map`. – reprogrammer Dec 04 '12 at 04:23
0

I did a pretty extensive evaluation of json-java libraries a few months ago, and chose json-smart: http://code.google.com/p/json-smart/

Has been working well.

ccleve
  • 15,239
  • 27
  • 91
  • 157