【问题标题】:Android Parse multiple JSON arraysAndroid 解析多个 JSON 数组
【发布时间】:2017-03-24 08:23:04
【问题描述】:

我尝试解析服务器返回给我的应用程序的多个 JSON 数组。

服务器返回的消息结构如下:

[json 对象][json 对象]

返回消息:

[{"latitude":"44.33","longitude":"44.33","name":"test1","Notification":"true"}][{"latitude":"44.33","longitude ":"44.33","name":"test2","Notification":"false"}]

现在我试图解析这个并获取通知状态(真/假),但我没有得到我需要的项目。

  try {

       JSONArray jr = new JSONArray(answer);
       JSONObject jb = (JSONObject)jr.getJSONObject(0);
       JSONArray nof = jb.getJSONArray("Notification");
       Log.d("Json", String.valueOf(nof));
  }catch(Exception e)
  {
       e.printStackTrace();
  }

如果有人可以帮助我了解我需要做些什么来实现我的使命,我会很高兴。

【问题讨论】:

  • 你可以使用 GSON 进行解析,它更容易。使用 GsonFormatter Android studio 插件创建模型类
  • 第一行的答案是什么?你有什么错误吗?
  • 是的,我收到下一个错误 - “java.lang.String 类型的通知中的值 true 无法转换为 JSONArray”
  • 您的返回消息不是有效的 JSON。尝试用一个键将这些数组包装在一个数组中。像这样:hastebin.com/amohisened.json
  • 您应该使用String nof = jb.getString("Notification"); 而不是JSONArray nof = jb.getJSONArray("Notification"); 并打印您可以简单地打印nof 的值,例如Log.d("Json", nof);

标签: android json parsing


【解决方案1】:

您的 Json 响应无效...

这是有效的 JSON:

  [
    [{
        "latitude": "44.33",
        "longitude": "44.33",
        "name": "test1",
        "Notification": "true"
    }],
    [{
        "latitude": "44.33",
        "longitude": "44.33",
        "name": "test2",
        "Notification": "false"
    }]
  ]

解析它:

try{
JSONArray json = new JSONArray(answer);
for(int i=0;i<json.length();i++){
     JSONArray array = json.getJSONArray(i);
         for(int i=0;i<array.length();i++){
            JSONObject object = array.getJSONObject(i);
            String Notification = object.getString("Notification");

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

【讨论】:

  • 他在尝试获取 Notification 的值时遇到错误,如果它是无效的 json,则异常应该是别的东西。我认为发布问题是错误的,请参阅有问题的 cmets
  • 这就是为什么我说...它不是有效的 JSON
  • 我尝试了这个,但是在“JSONArray array = json.getJSONArray(i);”行中我得到了错误-“org.json.JSONObject 类型为 0 的值不能转换为 JSONArray”
  • 好吧,你得到一个 JSON 对象的回复……发布完整的回复……你在问题上发布的回复是错误的!
  • 问题是当我检查他时数组的大小是 1 并且它需要是 2 ( json.length() )所以在你的代码中它只得到第一个元素并且产生问题.我如何获取数组的所有元素?
【解决方案2】:

无法整体解析该 Json 响应。形式上它不是 json 有效的,有两个 json 数组像这样连接起来不会产生有效的 json。

您可以将这些数组包装在一个唯一的 json 对象中,并且该对象现在可以使用您的代码进行解析。

{"array1":[],"array2":[]}

然后你可以实例化jsonObject并分别获取每个数组的名字

【讨论】:

  • 谢谢,但我如何才能将正确的返回字符串转换为您回答的类型?
  • 这取决于您在服务器端使用的语言来生成该 json
【解决方案3】:

创建一个响应的 POJO 让我们说 Notification.java

JSONArray resultArray = response.getJSONArray("result");// your json response 

// 使用谷歌的 Gson 库

编译'com.google.code.gson:gson:2.7.0'

List<Notification> notificationList = new    Gson().fromJson(String.valueOf(resultArray),Notification.class);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2015-03-19
    • 1970-01-01
    相关资源
    最近更新 更多