I agree that Google's Gson
is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple
:
// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;
@Test
public void json2Object() {
// given
String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
+ "\"address\" : \"some address\","
+ "\"someobject\" : {\"field\" : \"value\"}}";
// when
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
// then
@SuppressWarnings("unchecked")
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
.getSimpleName());
}
assertThat(object.get("age").toString(), is("20"));
}
Pros and cons of Gson
and json-simple
is pretty much like pros and cons of user-defined Java Object and Map
. The object you define is clear for all fields (name and type), but less flexible than Map
.