我有这个JSONObject,它作为来自第三方API的响应返回。
[
[
{
"msg": "hi",
"uuid": "fc8c5dd3-d46c-4945-894d-6160f830d815"
},
{
"msg": "hihe",
"uuid": "fc8c5dd3-d46c-4945-894d-6160f830d815"
}
],
14281343855179004,
14281349424008428
]
我该如何解析这个?
这就是我得到的
[[{"msg":"hi","uuid":"fc8c5dd3-d46c-4945-894d-6160f830d815"},{"msg":"hihe","uuid":"fc8c5dd3-d46c-4945-894d-6160f830d815"}],14281343855179005,14281349424008427]
我的代码
try {
JSONObject reader = new JSONObject(message.toString());
JSONObject sys = reader.getJSONObject("uuid");
String msg = sys.getString("msg");
System.out.println(msg);
} catch (JSONException e) {
e.printStackTrace();
}
答案 0 :(得分:2)
尝试,
JSONArray json = new JSONArray("[[{\"msg\":\"hi\",\"uuid\":\"fc8c5dd3-d46c-4945-894d-6160f830d815\"},{\"msg\":\"hihe\",\"uuid\":\"fc8c5dd3-d46c-4945-894d-6160f830d815\"}],14281343855179005,14281349424008427]");
JSONArray arr = json.getJSONArray(0);
for (int i = 0; i < arr.length(); i++){
String message = arr.getJSONObject(i).getString("msg");
String uuid = arr.getJSONObject(i).getString("uuid");
System.out.println("message : "+message);
System.out.println("uuid : "+uuid);
}
输出:
message : hi
uuid : fc8c5dd3-d46c-4945-894d-6160f830d815
message : hihe
uuid : fc8c5dd3-d46c-4945-894d-6160f830d815
答案 1 :(得分:1)
您可以直接使用JSONArray
代替JSONObject
public static void parseJson(String message) {
try {
JSONArray json = new JSONArray(message);
JSONArray elemArr = json.getJSONArray(0);
for (int i = 0; i < elemArr.length(); i++) {
String msg = elemArr.getJSONObject(i).getString("msg");
System.out.println("msg=" + msg);
String uuid = elemArr.getJSONObject(i).getString("uuid");
System.out.println("uuid=" + uuid);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
GSON是将Json转换为Java对象的好例子。
http://howtodoinjava.com/2014/06/17/google-gson-tutorial-convert-java-object-to-from-json/
谢谢, 帕