2015-04-23 34 views
0

我最近開始使用andorid。Android從php解析JSON與多個數組響應

如何解析動態json與PHP服務器的多個數組響應。

登錄響應與錯誤消息

{ 
    "status": 0, 
    "data": "No users found with given email." 
} 

和另一個

庫存清單

{ 
    "status": 1, 
    "data": { 
     "msg": "LoggedIn", 
     "user_id": "2" 
    } 
} 

登錄響應

{ 
    "status": 1, 
    "data": [ 
     { 
      "inventory_id": "33", 
      "apron_id": "123456", 
      "nickname": "uyi", 
      "location": "13", 
      "manufacture": "0", 
      "garment_type": "yuyh", 
      "color": "juki", 
      "core_material": "ytyt", 
      "Date_purchase": "2015-04-10", 
      "UID_no": "ikujki", 
      "serial": "iui", 
      "Batch": "ikk", 
      "Expiration": "2015-04-23", 
      "QTY": "898", 
      "apron_status": "0", 
      "apron_retire": "0", 
      "created_user": "2", 
      "created_time": "2015-04-10 05:22:38", 
      "update_time": "2015-04-10 05:22:38" 
     }, 
     { 
      "inventory_id": "32", 
      "apron_id": "12345mn", 
      "nickname": "gfhgh", 
      "location": "12", 
      "manufacture": "0", 
      "garment_type": "hgjyhj", 
      "color": "ytgtfghtg", 
      "core_material": "fhgfhy", 
      "Date_purchase": "2015-04-28", 
      "UID_no": "rtryttttttttt", 
      "serial": "hfh", 
      "Batch": "rtrrtyy", 
      "Expiration": "2015-03-17", 
      "QTY": "7688", 
      "apron_status": "0", 
      "apron_retire": "0", 
      "created_user": "2", 
      "created_time": "2015-04-10 05:15:54", 
      "update_time": "2015-04-10 05:15:54" 
     } 
    ] 
} 

在此先感謝。

+0

http://www.androidhive.info/2012/01/android -json-parsing-tutorial/ –

+0

你試過了什麼? – micky

+0

是的教程是明確的謝謝@MdAbdulGafur –

回答

1

獲得登錄響應,你可以像這樣

JSONObject jobj=new JSONObject(result.toString()); 

String status=jobj.getString("status"); 

if(status.equalsIgnoreCase("1")) 
{ 
    //login success 

    JSONObject Jdata=jobj.getJSONObject("data"); 

    String Message=Jdata.getString("msg"); 
    String UserId=Jdata.getString("user_id"); 
} 
else 
{ 
    //failure 
} 

和庫存清單,你可以像這樣

JSONObject jobj=new JSONObject(result.toString()); 

JSONArray arrData=jobj.getJSONArray("data"); 

for (int i = 0; i < arrData.length(); i++) 
{ 

     JSONObject jdata=arrData.getJSONObject(i); 

     //here u can get all field like this 

     String nickname=jdata.getString("nickname"); 
} 
+0

登錄數據Json不總是數組它將錯誤文本也說「無效登錄詳細信息「@Dhaiyur –

+0

@manikantag發表迴應 – Dhaiyur

+0

添加請參閱@Dhaiyur –

0

調查JSONObjectJSONArray類。

您可以非常簡單解析:

JSONObject json = new JSONObject(jsonString); 
int status = json.getInt("status"); 

同時使用數組和對象爲你的「數據」鍵會使事情刺激你。你應該考慮使用不同的密鑰或另一個密鑰,它會向你指明你正在閱讀的內容。

+0

登錄數據Json不是總是數組它將是錯誤文本也說「無效登錄詳細信息」@Knossos –