繁体   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