JSonParser出现空值

时间:2017-10-26 18:33:18

标签: java jsonparser

我正在遍历一个Json文件,似乎只获取空值。正如您所看到的,我试图通过索引访问它们。另外,我的整数很有趣,因为当我从json值使用Integer.parseInt时它并不喜欢。

JSON:

{
  "people": [
    {
      "name": "Kelly",
      "age": 50,
      "sex": "f",
      "illness": "Allergies"
    },
    {
      "name": "Josh",
      "age": 40,
      "sex": "m",
      "illness": "Sleep Apnea"
    },
    {
      "name": "Brad",
      "age": 20,
      "sex": "m",
      "illness": "Heart Disease"
    }
  ]
}

爪哇:

import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;


public class FileLoader {

    @SuppressWarnings("unchecked")
    public static void main(String args[]) {
        JSONParser parser = new JSONParser();
        int count = 0;

        try {
            Object obj = parser.parse(new FileReader(
                "Consumers.json"));

            JSONObject jsonObject = (JSONObject) obj;
            JSONArray array = (JSONArray) jsonObject.get("people");

            if(array.size() > 0) {
                while (count < array.size()) {

回答编辑

JSONObject people = (JSONObject) array.get(count);
                    String name = (String) people .get("name");
                    int age = (Integer) people .get("age");
                    String sex = (String) people .get("sex");
                    String illness = (String) people .get("illness");

完成修改

                    JSONObject people = (JSONObject) jsonObject.get(count);
                    String name = (String) jsonObject.get("name");
                    int age = (Integer) jsonObject.get("age");
                    String sex = (String) jsonObject.get("sex");
                    String illness = (String) jsonObject.get("illness");


                    System.out.println("\nPeople List " + count + ": ");
                    System.out.println("Name: " + name);
                    System.out.println("Age: " + age);
                    System.out.println("Sex: " + sex);
                    System.out.println("Illness: " + illness);
                    count++;
                }
            }

        } catch (Exception e) {
         e.printStackTrace();
        }
    }
}

我只需要读入文件,但我无法读取嵌套数组。所有值都返回null。我把它建成了一个maven项目。

1 个答案:

答案 0 :(得分:1)

这就是问题所在:

JSONObject people = (JSONObject) jsonObject.get(count);

jsonObject不是人的数组,它是顶级JSON对象。由于对象的顶级只有一个键(&#34; people&#34;),get(0),get(1),...的调用都返回null。

这是使用数组而不是jsonObject的正确行:

JSONObject people = (JSONObject) array.get(count);