首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用json-simple在Java中解析JSON文件

使用json-simple在Java中解析JSON文件
EN

Stack Overflow用户
提问于 2016-04-02 01:43:16
回答 2查看 13.8K关注 0票数 3

我已经创建了一个.json文件:

代码语言:javascript
复制
{
  "numbers": [
    {
      "natural": "10",
      "integer": "-1",
      "real": "3.14159265",
      "complex": {
        "real": 10,
        "imaginary": 2
      },
      "EOF": "yes"
    }
  ]
}

我想使用Json Simple来解析它,以便提取“自然”和“想象”的内容。

这是我到目前为止所写的内容:

代码语言:javascript
复制
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
String natural = (String) jsonObject.get("natural");
System.out.println(natural);

问题是natural的值是"null“而不是"10”。当我写jsonObject.get(“虚构的”)时,同样的事情也会发生。

我看了很多网站(包括StackOverflow),我遵循了大多数人写的相同的方式,但我无法解决这个问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-04-02 01:47:55

您需要首先在数组中找到JSONObject。您正在尝试查找顶级JSONObject的字段natural,该字段只包含字段numbers,因此它返回null,因为它找不到natural

要解决这个问题,您必须首先获取数字数组。

试着这样做:

代码语言:javascript
复制
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); //the location of the file
JSONObject jsonObject = (JSONObject) obj;
JSONArray numbers = (JSONArray) jsonObject.get("numbers");

for (Object number : numbers) {
    JSONObject jsonNumber = (JSONObject) number;
    String natural = (String) jsonNumber.get("natural");
    System.out.println(natural);
}
票数 4
EN

Stack Overflow用户

发布于 2016-04-02 01:46:21

文件中的对象只有一个属性,名为numbers

没有natural属性。

您可能希望检查该数组中的对象。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36362619

复制
相关文章

相似问题

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