使用 json-simple 解析 Java 中的 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36362619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing a JSON file in Java using json-simple
提问by George
I have created a .json file:
我创建了一个 .json 文件:
{
"numbers": [
{
"natural": "10",
"integer": "-1",
"real": "3.14159265",
"complex": {
"real": 10,
"imaginary": 2
},
"EOF": "yes"
}
]
}
and I want to parse it using Json Simple, in order to extract the content of the "natural" and the "imaginary".
我想用Json Simple解析它,以提取“自然”和“虚构”的内容。
This is what I have written so far:
这是我到目前为止所写的:
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);
The problem is that the value of natural is "null" and not "10". Same thing happens when I write jsonObject.get("imaginary").
问题是 natural 的值是“null”而不是“10”。当我编写 jsonObject.get("imaginary") 时也会发生同样的事情。
I have looked at many websites (including StackOverflow), I have followed the same way most people have written, but I am unable to fix this problem.
我查看了许多网站(包括 StackOverflow),我按照大多数人编写的方式进行了操作,但是我无法解决此问题。
回答by Jeremy Hanlon
You need to find the JSONObjectin the array first. You are trying to find the field naturalof the top-level JSONObject, which only contains the field numbersso it is returning nullbecause it can't find natural.
您需要先JSONObject在数组中找到。您正在尝试查找natural顶级的字段,该字段JSONObject仅包含该字段,numbers因此它正在返回,null因为它找不到natural。
To fix this you must first get the numbers array.
要解决此问题,您必须首先获取数字数组。
Try this instead:
试试这个:
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);
}
回答by SLaks
The object in your file has exactly one property, named numbers.
There is no naturalproperty.
您文件中的对象只有一个属性,名为numbers.
没有natural财产。
You probably want to examine the objects inside that array.
您可能想要检查该数组中的对象。

