2017-07-31 59 views
-9

我試圖將jsonstring轉換爲json對象。但它只轉換第一個元素。如何將jsonstring轉換爲android中的jsonobject?

這裏是我的代碼

String d = [{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}] 
JSONObject j = new JSONObject(d); 

其給予以下輸出

{"name":"kd","isMe":"yes","time":"10:12 AM"} 

我如何轉換這個字符串轉換成JSNOObject?

+0

那麼你應該將JSON對象轉換爲JSON陣列。遍歷數組然後打印出來。 – Tyson

回答

1

你可以嘗試這樣的,和你的根是JSON數組不JSONObject的

try { 
    JSONArray jsonArray = new JSONArray(d); 
    if(jsonArray != null) { 
     for (int i = 0; i < jsonArray.length(); i++) { 
      JSONObject jsonObject = jsonArray.optJSONObject(i); 

      if(jsonObject == null) { 
       continue; 
      } 

      String name = jsonObject.optString("name"); 
      String isMe = jsonObject.optString("isMe"); 
      String time = jsonObject.optString("time"); 

     } 
    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
} 
1

使用此

JSONObject jsonObject = new JSONObject(my_json_string); 
JSONArray jresult = jsonObject.getJSONArray("array_in_the_json_string"); 
相關問題