Parsing JSON seems like it is a pretty common topic of discussion on here. I have looked around and still have not found what I am looking for. Here is my code for my HttpC
In this case you can use the keys
method of the JSONObject
class. It will basically returns an Iterator
of the keys, that you can then iterate to get and put the values in a map:
try {
JSONObject jsonObject = new JSONObject(theJsonString);
Iterator keys = jsonObject.keys();
Map<String, String> map = new HashMap<String, String>();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, jsonObject.getString(key));
}
System.out.println(map);// this map will contain your json stuff
} catch (JSONException e) {
e.printStackTrace();
}
Note that Jackson can deserialize either of the two JSON examples very simply.
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> values = mapper.readValue(theJsonString, Map.class);
Gson can do it similarly simply if you're satisfied with a Map<String, String>
, instead of a Map<String, Object>
. Currently, Gson would need custom deserialization for a Map<String, Object>
.