the*_*spe 3 java string parsing json
我有一个转换字符串到json的问题.也就是说,我的json字符串是:
{"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"}]}
Run Code Online (Sandbox Code Playgroud)
我的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
System.out.println数组是:
[{"name":"level","value":"INFO"},{"name":"type","value":"Video Blocked On"},{"name":"cameraId","value":"722"},{"name":"userId","value":"1"}]
Run Code Online (Sandbox Code Playgroud)
但如果我打印obj是"{}",则是四次.所以它是正确的,因为数组有4个元素,但为什么它是空对象?我正在使用org.json.
谢谢
array.getJSONObject(i)已经返回了一个类型的对象,JSONObject你不需要将它传递给JSONObject类的构造函数.
简单地写
...
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
System.out.println("OBJ: " + obj);
}
...
Run Code Online (Sandbox Code Playgroud)