【问题标题】:How to loop and get the json object如何循环获取json对象
【发布时间】:2016-07-05 04:36:54
【问题描述】:
{
    "result": [
        {
            "id": "a258377906705d889422fd0b41c324b8",
            "coordinate": {
                "London": {
                    "x": 65.565709,
                    "y": 98.931235
                },
                "New_York": {
                    "x": 37.59751,
                    "y": 47.448718
                }
            }
        }
    ]
}

如果我有一个像上面这样的 json, 如何循环获取x,y 坐标,如果我要获取更多数据,我该如何获取?

如果我还想将LondonNew York 添加到array list,我该怎么做(不能直接添加名称,因为有两个以上的数据)?

【问题讨论】:

  • 研究使用 JSON 解析器。

标签: json arraylist getjson


【解决方案1】:

您可以解析它,然后使用JSON.parse( insert json here ) 使用它。

基本上它的作用是获取您的 JSON 字符串并将其转换为可用的 JSON。

要将新对象添加到另一个对象中,我建议使用Object.assign()。 详情可以参考这里:Link

以下是网站给出的示例:

var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };

var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.

Object.assign() 将目标对象作为第一个参数,并使用我们提供的其他参数对其进行修改。

在你的情况下,你可以像这样更新你的对象:

var countryCoord = JSON.parse(yourjsondata); // parse the json that you included
 Object.assign(countryCoord, newCoord, newCoord2,...etc); //this would update countryCoord alone

在线解析器:Link

【讨论】:

    【解决方案2】:

    您必须处理 json 并了解从哪里获取 JSONObject 以及从哪里获取 JSONArray,在此基础上您可以相应地解析 JSON。

    有关在 Java 中解析带有嵌套项的 json 对象的更多信息,请参阅链接:

    Retrieving nested arrays values with java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多