[英]Using Json-simple to parse an array of objects from a file
我在使用 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
Object obj = parser.parse(new FileReader("sample.json"));
// convert object to JSONArray
JSONArray jsonArray = (JSONArray ) obj;
然后你可以遍历jsonArray
。
jsonArray.forEach(item -> {
System.out.println(item);
// Do stuff
});
我认为您的 JSON 在 JSON 标准方面无效(请参阅JSON.org )。 JSON 应以“{”开头并以“}”结尾。 我认为该数组无法以标准方式访问,因为它缺少密钥。 如果可能,您应该将您的 JSON 放在之间(或者只是将其连接到您的代码中的 JSON 字符串):
{ "array":
//yourJson
}
然后,您可以使用以下内容访问 Array:
JSONArray array = (JSONArray) jsonObject.get("array");
Iterator iter = array.iterator();
while (iter.hasNext()) {
System.out.println( ( iter.next() ).get("title") );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.