【发布时间】:2017-08-11 21:38:27
【问题描述】:
我在使用 json-simple 解析 json 对象数组时遇到问题。
假设以下report 对象数组:
[
{
"title": "Test Object 1",
"description": "complicated description...",
"products": null,
"formats": ["csv"]
},
{
"title": "Test Object 2",
"description": "foo bar baz",
"products": ["foo"],
"formats": ["csv", "pdf", "tsv", "txt", "xlsx"]
},
{
"title": "Test Object 3",
"description": "Lorem Ipsum stuff...",
"products": null,
"formats": ["pdf", "xlsx"]
}
]
在以下代码中,从文件中读取后,我如何遍历数组中的每个对象来执行操作?
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class JsonReader {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("sample.json"));
//convert object to JSONObject
JSONObject jsonObject = (JSONObject) obj;
//reading the string
String title = (String) jsonObject.get("title");
String description = (String) jsonObject.get("description");
//Reading an array
JSONArray products = (JSONArray) jsonObject.get("products");
JSONArray formats = (JSONArray) jsonObject.get("formats");
//Log values
System.out.println("title: " + title);
System.out.println("description: " + description);
if (products != null) {
for (Object product : products) {
System.out.println("\t" + product.toString());
}
} else {
System.out.println("no products");
}
if (formats != null) {
for (Object format : formats) {
System.out.println("\t" + format.toString());
}
} else {
System.out.println("no formats");
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行调试器,似乎 jsonObject 正在存储数组,但我不确定如何获取它。为每个循环创建一个似乎不起作用,因为 JSONObject 不可迭代。
【问题讨论】:
-
看来您要解析的 JSON 是 JSONArray,而不是单个 JSONObject。如果有帮助的话。
标签: java json json-simple