使用 json-simple 解析 Java 中的 JSON 文件
Parsing a JSON file in Java using json-simple
我创建了一个 .json 文件:
{
"numbers": [
{
"natural": "10",
"integer": "-1",
"real": "3.14159265",
"complex": {
"real": 10,
"imaginary": 2
},
"EOF": "yes"
}
]
}
我想使用 Json 简单地解析它,以便提取 "natural" 和 "imaginary" 的内容。
这是我到目前为止写的:
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("imaginary").
时也会发生同样的事情
我看了很多网站(包括Whosebug),我按照大多数人写的方式来做,但我无法解决这个问题。
您文件中的对象只有一个 属性,名称为 numbers
。
没有natural
属性。
您可能想要检查该数组中的对象。
你需要先找到数组中的JSONObject
。您正在尝试查找顶级 JSONObject
的字段 natural
,它只包含字段 numbers
所以它返回 null
因为它找不到 natural
.
要解决此问题,您必须先获取数字数组。
试试这个:
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);
}
我创建了一个 .json 文件:
{
"numbers": [
{
"natural": "10",
"integer": "-1",
"real": "3.14159265",
"complex": {
"real": 10,
"imaginary": 2
},
"EOF": "yes"
}
]
}
我想使用 Json 简单地解析它,以便提取 "natural" 和 "imaginary" 的内容。
这是我到目前为止写的:
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("imaginary").
时也会发生同样的事情我看了很多网站(包括Whosebug),我按照大多数人写的方式来做,但我无法解决这个问题。
您文件中的对象只有一个 属性,名称为 numbers
。
没有natural
属性。
您可能想要检查该数组中的对象。
你需要先找到数组中的JSONObject
。您正在尝试查找顶级 JSONObject
的字段 natural
,它只包含字段 numbers
所以它返回 null
因为它找不到 natural
.
要解决此问题,您必须先获取数字数组。
试试这个:
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);
}