Converting string to json doesn't work java
I have a problem converting string to json. Namely, my json string:
{"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:
[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]
but if I type obj it's "{}" four times. So this is correct because the array has 4 elements, but why is it an empty object? I am using org.json.
thank
source to share
You call the constructor JSONObject(Object)
by passing in JSONObject
(an element in the array). This constructor is documented as:
Create JSONObject from object using bean getters. It reflects all the public methods of the object. For each of the methods without parameters, and a name starting with
"get"
or"is"
followed by an uppercase letter, the method is called, and the key and value returned by the getter method are placed in a new JSONObject. [...]
Now JSONObject
has nothing to match the getter bean, so you have no keys. You don't want to be treated JSONObject
like a bean.
This is why your current code is not working. To fix this, simply don't call the constructor - instead, use the fact that the array element already exists JSONObject
:
JSONObject obj = array.getJSONObject(i);
Exit with this change:
OBJ: {"name":"level","value":"INFO"}
OBJ: {"name":"type","value":"Video Blocked On"}
OBJ: {"name":"cameraId","value":"722"}
OBJ: {"name":"userId","value":"1"}
source to share