2015-04-04 54 views
2

我有這個作爲第三方API響應返回的JSONObject。在java中解析這個JSON?

[ 
[ 
    { 
     "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(); 
      } 
+1

你能告訴我們你的代碼 – Juxhin 2015-04-04 08:13:05

+0

你可以使用一個搜索引擎,尋找一個Java庫,會爲你做這項工作。你可以在你的項目中包含幾個好的庫。 – MWiesner 2015-04-04 08:18:10

+0

@Juxhin更新了問題,請檢查 – WISHY 2015-04-04 08:18:10

回答

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

你可以直接使用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(); 
    } 
    } 
+0

請刪除評論然後:p – Iqbal 2015-04-04 08:57:12