[英]How can I loop over a json array in android?
I have a string comming from php looking exactly like that : "[{"id":"0","noteText":"Noteeeeeeee","date":"1232131","author":"John","authorId":"1"},{"id":"1","noteText":"Noteeeeeeee","date":"1232131","author":"Rob","authorId":"1"}]"
我有一个来自php的字符串,看起来就像这样: "[{"id":"0","noteText":"Noteeeeeeee","date":"1232131","author":"John","authorId":"1"},{"id":"1","noteText":"Noteeeeeeee","date":"1232131","author":"Rob","authorId":"1"}]"
Then in my onCreate
in the mainActiviry.java
I got to this point : 然后在mainActiviry.java
onCreate
中,我达到了这一点:
String json = allNotes;
//System.out.println("String to Json Array Stmt");
JsonParser parser = new JsonParser();
JsonElement notes = parser.parse(allNotes);
JsonArray notesArr = notes.getAsJsonArray();
My goal is to parse the json string to array of json objects, then loop over it and feed it to a ListView
. 我的目标是将json字符串解析为json对象的数组,然后对其进行循环并将其提供给ListView
。 The problem is that I cannot get there, since I am failing to loop over this jsonArray
. 问题是我无法到达那里,因为我无法遍历此jsonArray
。 My java knowledge is too limited, so other questions didn't help me much. 我的Java知识太有限,因此其他问题并没有太大帮助。
Can someone help, please? 有人可以帮忙吗?
ps i am using gson ps我正在使用gson
Traverse the JsonArray
using size
while fetching the JsonElement
using get
function using i
index and convert it into JsonObject
using getAsJsonObject()
function 使用size
遍历JsonArray
同时使用使用i
索引的get
函数获取JsonElement
并使用getAsJsonObject()
函数将其转换为JsonObject
JsonParser parser = new JsonParser();
JsonElement notes = parser.parse(s);
JsonArray notesArr = notes.getAsJsonArray();
for (int i = 0; i < notesArr.size(); i++) {
// get your jsonobject
JsonObject obj = notesArr.get(i).getAsJsonObject();
// do the same for the rest of the elements like date , author ,authorId
String id,noteText,author;
// fetch data from object
id = obj.get("id").getAsString();
noteText = obj.get("noteText").getAsString();
author = obj.get("author").getAsString();
// Store these values in list or objects you want
System.out.println(id);
System.out.println(noteText);
System.out.println(author);
}
output : 输出:
0
Noteeeeeeee
John
1
Noteeeeeeee
Rob
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.