Reputation: 1189
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"}]"
Then in my onCreate
in the mainActiviry.java
I got to this point :
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
. The problem is that I cannot get there, since I am failing to loop over this jsonArray
. My java knowledge is too limited, so other questions didn't help me much.
Can someone help, please?
p.s. i am using gson
Upvotes: 0
Views: 2199
Reputation: 37404
Traverse the JsonArray
using size
while fetching the JsonElement
using get
function using i
index and convert it into JsonObject
using getAsJsonObject()
function
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
Upvotes: 5