I have a problem with convert string to json. Namely, my json string is:
{"serverId":2,"deviceId":736,"analysisDate":"2017-05-11T07:20:27.713Z","eventType":"Logs","eventAttributes":[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]}
My code:
try {
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray("eventAttributes");
System.out.println("ARRAY: " + array);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = new JSONObject(array.getJSONObject(i));
System.out.println("OBJ: " + obj);
}
} catch (JSONException ex) {
Exceptions.printStackTrace(ex);
}
System.out.println array is:
[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]
but if I print obj is "{}", four times. So it is correct, because array has 4 elements, but why it is empty object? I'm using org.json.
Thanks
You're calling the JSONObject(Object)
constructor, passing in a JSONObject
(the element in the array). That constructor is documented as:
Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with
"get"
or"is"
followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. [...]
Now JSONObject
itself doesn't have anything that fits a bean getter, so you end up with no keys. You don't want to treat the JSONObject
as a bean.
That's why your current code doesn't work. To fix it, just don't call the constructor - instead, use the fact that the array element is already a JSONObject
:
JSONObject obj = array.getJSONObject(i);
Output with that change:
OBJ: {"name":"level","value":"INFO"}
OBJ: {"name":"type","value":"Video Blocked On"}
OBJ: {"name":"cameraId","value":"722"}
OBJ: {"name":"userId","value":"1"}
See more on this question at Stackoverflow