org.json.JSONException:Name JSON 提取错误没有值



当我尝试从以下 JSON 中获取"名称"的值时,我收到此错误:

{
  "edges": [
    {
      "node": {
        "Name": "Sunday River",
        "Latitude": 44.4672,
        "Longitude": 70.8472
      }
    },
    {
      "node": {
        "Name": "Sugarloaf Mountain",
        "Latitude": 45.0314,
        "Longitude": 70.3131
      }
    }
  ]
}

这是我用来尝试访问这些值的代码片段,但我现在只是在测试获取"名称":

String[] nodes = stringBuilder.toString().split("edges");
nodes[1] = "{" + """ + "edges" + nodes[1];
String s = nodes[1].substring(0,nodes[1].length()-3);
Log.d(TAG, s);
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.getJSONArray("edges");
ArrayList<String> allNames = new ArrayList<String>();
ArrayList<String> allLats = new ArrayList<String>();
ArrayList<String> allLongs = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
    JSONObject node = jsonArray.getJSONObject(i);
    Log.d(TAG, node.toString(1));
    String name = node.getString("Name");
    Log.d(TAG, name);
}

我的输出如下所示:

{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}
{
    "node": {
        "Name": "Sunday River",
        "Latitude": 44.4672,
        "Longitude": 70.8472
    }
}
org.json.JSONException: No value for Name

我知道我可以使用optString而不会收到错误,但这不会给我存储在每个节点中的数据。

下面是一个适用于未更改 JSON 的版本:

public static void main(String... args)
{
    String json = "{"data":{"viewer":{"allMountains":{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}}}";
    JSONObject obj = new JSONObject(json);
    JSONObject data = obj.getJSONObject("data");
    JSONObject viewer = data.getJSONObject("viewer");
    JSONObject allMountains = viewer.getJSONObject("allMountains");
    // 'edges' is an array
    JSONArray edges = allMountains.getJSONArray("edges");
    for (Object edge : edges) {
        // each of the elements of the 'edge' array are objects
        // with one property named 'node', so we need to extract that
        JSONObject node = ((JSONObject) edge).getJSONObject("node");
        // then we can access the 'node' object's 'Name' property
        System.out.println(node.getString("Name"));
    }
}

最新更新