如何使用Json.simple解析Java中的JSONArray? [英] How do I parse a JSONArray in Java with Json.simple?
问题描述
我正在尝试读取这样的JSON文件:
I am trying to read a JSON file like this:
{
"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."
}
]
}
]
}
它是用于学校练习的.我选择尝试使用JSON.simple(来自GoogleCode),但是我对另一个JSON库开放.我听说过杰克逊和格森:它们比JSON.simple好吗?
It's for a school exercise. I chose to try and use JSON.simple (from GoogleCode), but I am open to another JSON library. I heard about Jackson and Gson: Are they better than JSON.simple?
这是我当前的Java代码:
Here is my current Java code:
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);
}
我检查了很多示例(有些在Stack上!),但从未找到解决问题的方法.
I checked out a lot of examples (some on Stack!) but I never found the solution to my problem.
也许我们无法使用JSON.simple做到这一点?您有什么建议?
Maybe we can't do this with JSON.simple? What do you recommend?
推荐答案
您永远不会为jsonObject
分配新值,因此在循环内它仍然引用完整的数据对象.我想您想要类似的东西:
You never assign a new value to jsonObject
, so inside the loop it still refers to the full data object. I think you want something like:
JSONObject slide = i.next();
String title = (String)slide.get("title");
这篇关于如何使用Json.simple解析Java中的JSONArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!