簡體   English   中英

如何一起解析json對象和json數組

[英]How parse json object and json array together

我有兩種情況的Json輸出。 一個是找到的數據,我有一個json數組和一個json對象,如下所示:

{"data":"yes"}[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]

其他情況是找不到數據:

{"data":"no"}

只是一個json對象。

如何在Android客戶端中解析此數據以支持兩個情景?

首先,您應該在http://jsonlint.com/中驗證您的json(如果進行測試),那么您會發現這是錯誤的json。 因此,為正確起見,在您的服務器中,您的響應應如下所示:

{"data":"yes","response":[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}

在這種情況下,在android中

JSONObject jsonObj = new JSONObject(response); 
if (jsonObj.getString("data").compareTo("yes") == 0) {
   JSONArray jsonArray = jsonObj.getJSONArray("response");
   //To-Do another code
}

就這樣

這是一種可能的情況:(您需要修復json格式)

成功-

 string resultJSON = 
   {"success":true,
      "data":[
          {"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},
          {"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}

失敗-

string resultJSON =
    {"success":false}

然后

JSONObject jsonRoot  = new JSONObject(resultJSON);
 bool isSuccess = jsonRoot.getBoolean("success");
 if (isSuccess) {
  // do the array parser
  for(int i=0; i<jsonData.lenght;i++) {
        JSONObject jsonObj = jsonData.getJSONObject(i);
        String id = jsonObj.getString("id");   // get the value of id
        String desc = jsonObj.getString("desc");  // and so on...
  }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM