[英]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.