我在使用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正在存储数组,但我不确定如何访问它。创建for each循环似乎不起作用,因为JSONObject是不可迭代的。
发布于 2020-02-12 15:45:29
您可以将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
});发布于 2017-08-12 06:29:19
我认为您的JSON在JSON标准方面是无效的(请参阅JSON.org)。JSON应以'{‘开头,以’}‘结尾。我认为数组不会以标准的方式访问,因为它缺少一个键。如果可能,您应该将JSON放在以下内容之间(或者在代码中将其与JSON字符串连接起来):
{ "array":
//yourJson
}然后你可以像这样访问数组:
JSONArray array = (JSONArray) jsonObject.get("array");
Iterator iter = array.iterator();
while (iter.hasNext()) {
System.out.println( ( iter.next() ).get("title") );
}https://stackoverflow.com/questions/45644144
复制相似问题