首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSonParser出现空

JSonParser出现空
EN

Stack Overflow用户
提问于 2017-10-26 18:33:18
回答 1查看 433关注 0票数 0

我正在遍历Json文件,似乎只得到空。正如您所看到的,我正在尝试使用索引访问它们。另外,我的整数很有趣,因为它不喜欢从json值中使用Integer.parseInt。

JSON:

代码语言:javascript
复制
{
  "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"
    }
  ]
}

Java:

代码语言:javascript
复制
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()) {

应答编辑

代码语言:javascript
复制
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");

完成编辑

代码语言:javascript
复制
                    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项目来构建。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-26 21:57:15

这就是问题所在:

代码语言:javascript
复制
JSONObject people = (JSONObject) jsonObject.get(count);

jsonObject不是人员数组,而是顶级JSON对象。由于对象的顶层只有一个键("people"),所以调用get(0)、get(1)、.全部返回null。

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

代码语言:javascript
复制
JSONObject people = (JSONObject) array.get(count);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46961468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档