0

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

3

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.