I was wondering, is there any JSON library which enable me
- Get a key to value map, out from JSON String (JSONObject able to do this)
- Get a Java object, out from JSON String (Google Gson able to do this)
The following both print value
package jsontest;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author yccheok
*/
public class Main {
public static class Me {
public String key;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws JSONException {
final String s = "{\"key\" : \"value\"}";
// Feature 1
final JSONObject jsonObject = new JSONObject("{\"key\" : \"value\"}");
System.out.println(jsonObject.getString("key"));
// Feat开发者_开发百科ure 2
Gson gson = new Gson();
Me me = gson.fromJson(s, Me.class);
System.out.println(me.key);
}
}
Currently, I have to use 2 different libraries to achieve the above JSON related task. Is there any libraries which able to do both 2 tasks?
You can use Jackson.
It has a databinding solution (like Gson) and a tree model view (like JSONObject)
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
public class Main {
public static class Me {
public String key;
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "{\"key\" : \"value\"}";
// Feature 1
JsonNode rootNode = mapper.readValue(json, JsonNode.class);
System.out.println(rootNode.get("key").getTextValue());
// Feature 2
Me value = mapper.readValue(json, Me.class);
System.out.println(value.key);
}
}
I don't know how I missed this the first time, but you can do this in Gson using its JsonParser
:
JsonParser parser = new JsonParser();
JsonElement rootElement = parser.parse(reader);
Previous answer (no need to do this)
I'm not sure if Gson has some easier built in way to do this, but this seems to work:
public enum JsonElementDeserializer implements JsonDeserializer<JsonElement> {
INSTANCE;
public JsonElement deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return json;
}
}
And then:
Gson gson = new GsonBuilder().registerTypeAdapter(JsonElement.class,
JsonElementDeserializer.INSTANCE).create();
JsonElement rootElement = gson.fromJson(reader, JsonElement.class);
精彩评论