有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法使用json对象NPE读取jsonarray

我是JSON格式和Java的新手。如果我遗漏了一点,请通知我

这是我的解析器代码。路径是正确的。如果我写的话,我可以读到布拉布拉的部分。但这是一个例子。大小始终为空。所以我无法阅读文件的其余部分。 我使用json simple 1.1.1

   `JSONParser parser = new JSONParser();
        Object obj = parser.parse(path);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray examples= (JSONArray) jsonObject.get("example");
        System.out.println("Example SIZE:" + examples.size());`

我无法共享确切的json文件,但其格式与我的json类似:

{
  "examples":{
    "blabla":"blabla",
    "example":[
      {
        "id":"1",
        "firstName":"Leonardo",
        "lastName":"DiCaprio",
        "photo":"http://1.bp.blogspot.com/-zvS_6Q1IzR8/T5l6qvnRmcI/AAAAAAAABcc/HXO7HDEJKo0/s200/Leonardo+Dicaprio7.jpg",
        "movieandpoint":[
          {
            "movie":"Inception",
            "point":"9.1"
          },
          {
            "movie":"Catch me if you can",
            "point":"8"
          }
        ],
        "decision":{
          "user":"admin",
          "#text":"ok"
        },
        "movieandpoint#1":[
          {
            "movie":"another one",
            "point":"7"
          }
        ]
      },
      {
        "id":"2",
        "firstName":"Johnny",
        "lastName":"Depp",
        "photo":"http://4.bp.blogspot.com/_xR71w9-qx9E/SrAz--pu0MI/AAAAAAAAC38/2ZP28rVEFKc/s200/johnny-depp-pirates.jpg",
        "movieandpoint":[
          {
            "movie":"Sweeny Tod",
            "point":"9"
          },
          {
            "movie":"Yoga Hosers",
            "point":"5"
          }
        ],
        "decision":{
          "user":"admin",
          "#text":"ok"
        },
        "movieandpoint#1":[
          {
            "movie":"another",
            "point":"9"
          }
        ]
      }
    ]
  }
}

共 (1) 个答案

  1. # 1 楼答案

    你必须从父母那里读给孩子听。像下面这样的东西会有用的。首先,您必须阅读“示例”jsonobject,然后是子对象“exapple”。顺便说一句,我不能用你的json文件运行这个,就像其他用户在评论中提到的那样,json文件在结构上是不正确的

    JSONParser parser = new JSONParser();
        Object obj = parser.parse(aa);
        org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) obj;
        org.json.simple.JSONObject object1 = (org.json.simple.JSONObject) jsonObject.get("examples");
       JSONArray examples = (JSONArray) object1.get("example");
        System.out.println("Example SIZE:" + examples.size());