Simple situation -
I tried gson, package from json.org,
With Gson (assuming that you have on object {...}
on the top level of your json file):
final JsonParser parser = new JsonParser();
final JsonElement jsonElement = parser.parse(new FileReader("/path/to/myfile"));
final JsonObject jsonObject = jsonElement.getAsJsonObject();
for (final Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final String key = entry.getKey();
final JsonElement value = entry.getValue();
....
}
You should certainly avoid re-parsing the json from a string. Use something like:
... else if (value.isJsonArray()) {
final JsonArray jsonArray = value.getAsJsonArray();
if (jsonArray.size() == 1) {
runThroughJson(jsonArray.get(0));
} else {
// perform some error handling, since
// you expect it to have just one child!
}
}
We use Jaskson parser, here are the sample code:
protected T getJsonObject(InputStream inputStream, Class<T> className) throws JsonParseException,
JsonMappingException, IOException {
// Deserialize input to Json object
ObjectMapper mapper = new ObjectMapper();
T jsonSource = mapper.readValue(inputStream, className);
return jsonSource;
}
Here is the code how to invoke it:
JsonEmployee jsonEmployee = getJsonObject(inputStream, JsonEmployee.class);
JsonEmployee.java is just POJO
XStream is good for JSON: http://x-stream.github.io/json-tutorial.html
Due to XStream's flexible architecture, handling of JSON mappings is as easy as handling of XML documents. All you have to do is to initialize XStream object with an appropriate driver and you are ready to serialize your objects to (and from) JSON.