如何在Java解析JSONArray与Json.simple? [英] How parsing JSONArray in Java with Json.simple?
问题描述
我试着去阅读这样的JSON文件:
I try 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."
}
]
}
]
}
这是一所学校的exercice,我选择尝试使用JSON.simple(从谷歌code),但我开到其他的JSON库。我听说杰克逊和GSON:他们比JSON.simple好
It's for a school exercice, I choose to try to use JSON.simple (from GoogleCode) but I am open to another JSON libraries. I heard about Jackson and Gson: they are better than JSON.simple?
下面我当前的Java code:
Here 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);
}
我查了很多例子(有些堆栈!),但我从来没有发现我的问题的解决方案。
I check a lot of example (some in Stack!) but I never found the solution of my problem.
也许我们不能做到这一点与JSON.simple?你有什么建议?
Maybe we can't do that 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");
这篇关于如何在Java解析JSONArray与Json.simple?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!