我尝试读取这样的JSON文件:
{
"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."
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
这是一个学校练习,我选择尝试使用JSON.simple(来自GoogleCode),但我对另一个JSON库开放.我听说过Jackson和Gson:他们比JSON.simple好吗?
这是我目前的Java代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
我查了很多例子(有些在Stack!)但是我从未找到问题的解决方案.
也许我们不能用JSON.simple做到这一点?您有什么推荐的吗?
Rus*_*ser 15
您永远不会为其分配新值jsonObject,因此在循环内它仍然指向完整的数据对象.我想你想要的东西:
JSONObject slide = i.next();
String title = (String)slide.get("title");
Run Code Online (Sandbox Code Playgroud)
Jib*_*ibi 15
它的工作原理!Thx Russell.我将完成我的练习,并尝试GSON看看差异.
新代码在这里:
JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides");
Iterator i = slideContent.iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
String title = (String)slide.get("title");
System.out.println(title);
}
Run Code Online (Sandbox Code Playgroud)