【问题标题】:Is this a correct JSON format {"coord":{"lat":37.4056,"lon":-122.0775}} [duplicate]这是正确的 JSON 格式吗 {"coord":{"lat":37.4056,"lon":-122.0775}} [重复]
【发布时间】:2015-08-29 20:15:44
【问题描述】:

我了解正确的 JSON 格式如下:

{"coord":[{"lat":37.4056,"lon":-122.0775}]}

但是我收到了这种格式的数据

{"coord":{"lat":37.4056,"lon":-122.0775}}

如果这是正确的 JSON 格式,如何在 Java 中解析?

【问题讨论】:

    标签: java json


    【解决方案1】:

    Json 中,{} 括号表示一个对象,而[] 括号表示一个数组。

    您的第一个示例包含一个数组,其中一个对象包含latlon 属性,该对象由data.coord[0].lat 访问。
    您的第二个示例是包含具有 latlon 属性的对象的对象。
    也就是说,没有数组,只是一个对象。该对象由data.coord.lat 访问。

    两者都是正确的 json。

    您几乎以相同的方式解析它们,它们只是不同的类型(coord 下的对象或数组)。

    // Parse:
    JSONObject obj = new JSONObject(jsondatastring);
    // Fetching the object:
    JSONObject coord = obj.getJSONObject("coord");
    // Or fetching the array:
    JSONArray coords = obj.getJSONArray("coord");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 2015-09-02
      • 2012-01-08
      相关资源
      最近更新 更多