简体   繁体   English

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

[英]org.json.JSONException: No value for Name JSON extraction error

I am getting this error when I try to get the value for "Name" out of the following JSON: 当我尝试从以下JSON中获取“名称”的值时,出现此错误:

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

This is the snippet of code I am using to try and access these values, but I am just testing getting "Name" for now: 这是我用来尝试访问这些值的代码段,但是我现在只是在测试获取“名称”:

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);

}

My output looks like this: 我的输出如下所示:

{"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

I understand that I could use optString and not get the error, but that will not give me the data stored in each node. 我知道我可以使用optString而不得到错误,但是那不会给我存储在每个节点中的数据。

Here is a version that works with your unaltered JSON: 这是与未更改的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"));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM