我目前正在为Android制作圣经经文应用程序,我遇到的问题可能很常见,但我发现很难实现,因为我是初学者。
如何从下面采样的json数据中获取字符串中的每个信息?
{
"book": "1 John",
"chapters": [{
"chapter": "1",
"verses": [{
"1": "That which was from the beginning, which we have heard, which we have seen with our eyes, which we have looked upon, and our hands have handled, of the Word of life;"
}, {
"2": "(For the life was manifested, and we have seen it, and bear witness, and shew unto you that eternal life, which was with the Father, and was manifested unto us;)"
}]
}]
如果我要获取每个数据以便我可以将其用作字符串或列表,我应该使用如下代码吗?如何更改代码以便从json获取数据?我很乐意听到你的消息!
JSONObject obj = new JSONObject(script);
JSONArray chapters = obj.getJSONArray("chapters");
ArrayList < HashMap < String, String >> formList = new ArrayList < HashMap < String, String >> ();
HashMap < String, String > m_li;
for (int i = 0; i < chapters.length(); i++) {
JSONObject jo_inside = chapters.getJSONObject(i);
String formula_value = jo_inside.getString("chapters");
String url_value = jo_inside.getString("verse");
}
答案 0 :(得分:1)
更好的数据表示将是这样的。
{
"book": "1 John",
"chapters": [
{
"chapter": "1",
"verses": [
{
"1": "That which was from the beginning, which we have heard, which we have seen with our eyes, which we have looked upon, and our hands have handled, of the Word of life;"
},
{
"2": "(For the life was manifested, and we have seen it, and bear witness, and shew unto you that eternal life, which was with the Father, and was manifested unto us);"
}
]
}
]
}
如您所见,我们有两个级别的列表,在JSON中由[]表示。我还删除了不必要的复杂JSON对象。
JSONObject obj = new JSONObject(script);
JSONArray chaptersList = obj.getJSONArray("chapters");
ArrayList<HashMap<String, String>> chapterHash = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < chaptersList.length(); i++) {
JSONObject chapter = chaptersList.getJSONObject(i);
String chapterId = chapter.getString("chapter");
chapterHash.add(new HashMap<String, String>());
JSONArray versesList = chapter.getJSONArray("verses");
for(int j=0;j < versesList.length();j++){
JSONObject verse = versesList.getJSONObject(j);
for(int k = 0; k<verse.names().length(); k++){
String verseKey = verse.names().getString(k);
String verseContent = verse.getString(verseKey);
chapterHash.get(i).put(verseKey,verseContent);
}
}
}