【问题标题】:How parse json object and json array together如何一起解析 json 对象和 json 数组
【发布时间】:2014-12-02 19:42:56
【问题描述】:

我有两种 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 客户端解析这些数据以支持两种情况?

【问题讨论】:

  • “yes”版本不是合法的json,所以解析不会有问题...
  • 如何实现该模式?使用两个数组?

标签: android json web-services


【解决方案1】:

首先,您应该在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
}

仅此而已

【讨论】:

    【解决方案2】:

    这是一种可能的情况:(您需要修复您的 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...
      }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-01
      • 2019-01-14
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2016-11-20
      • 2013-03-22
      • 1970-01-01
      相关资源
      最近更新 更多