tôi cố gắng để đọc một tệp JSON như thế này:Cách phân tích cú pháp JSONArray trong Java với Json.simple?
{
"presentationName" : "Here some text",
"presentationAutor" : "Here some text",
"presentationSlides" : [
{
"title" : "Here some text.",
"paragraphs" : [
{
"value" : "Here some text."
},
{
"value" : "Here some text."
}
]
},
{
"title" : "Here some text.",
"paragraphs" : [
{
"value" : "Here some text.",
"image" : "Here some text."
},
{
"value" : "Here some text."
},
{
"value" : "Here some text."
}
]
}
]
}
Đó là một exercice trường, tôi chọn cách cố gắng sử dụng JSON.simple (từ GoogleCode) nhưng tôi mở cửa cho một thư viện JSON. Tôi nghe nói về Jackson và Gson: chúng tốt hơn JSON.simple?
Đây mã Java hiện tại của tôi:
Object obj = parser.parse(new FileReader("file.json"));
JSONObject jsonObject = (JSONObject) obj;
// First I take the global data
String name = (String) jsonObject.get("presentationName");
String autor = (String) jsonObject.get("presentationAutor");
System.out.println("Name: "+name);
System.out.println("Autor: "+autor);
// Now we try to take the data from "presentationSlides" array
JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides");
Iterator i = slideContent.iterator();
while (i.hasNext()) {
System.out.println(i.next());
// Here I try to take the title element from my slide but it doesn't work!
String title = (String) jsonObject.get("title");
System.out.println(title);
}
tôi kiểm tra rất nhiều ví dụ (một số trong Stack!) Nhưng tôi không bao giờ tìm thấy các giải pháp của vấn đề của tôi.
Có lẽ chúng ta không thể làm điều đó với JSON.simple? Bạn đề xuất món gì?
Đây hoàn toàn là một cuộc tranh luận tôn giáo đối với tôi, nhưng tôi rất thích [Google GSON] (https://code.google.com/p/google-gson/) trên các trình phân tích cú pháp JSON khác. – david99world
Thx để nhận xét. Nếu chương trình này hoạt động, tôi sẽ thử GSON sớm để đưa ra quyết định của riêng tôi! – Jibi