2017-06-19 25 views
0

我有一個字符串從PHP正在添加正是在尋找這樣的:"[{"id":"0","noteText":"Noteeeeeeee","date":"1232131","author":"John","authorId":"1"},{"id":"1","noteText":"Noteeeeeeee","date":"1232131","author":"Rob","authorId":"1"}]"我如何循環播放android中的json數組?

然後我onCreatemainActiviry.java我得到了這一點:

String json = allNotes; 
    //System.out.println("String to Json Array Stmt"); 
    JsonParser parser = new JsonParser(); 
    JsonElement notes = parser.parse(allNotes); 
    JsonArray notesArr = notes.getAsJsonArray(); 

我的目標是將JSON字符串解析到數組json對象,然後遍歷它並將其提供給ListView。問題是我無法到達那裏,因爲我無法循環這個jsonArray。我的Java知識太有限了,所以其他問題對我沒有多大幫助。

有人可以幫忙嗎?

p.s.我使用GSON

+0

我使用GSON –

+3

https://stackoverflow.com/questions/3408985/json-array-iteration-in-android-java –

+0

[Android/Java中的JSON數組迭代]的可能副本(https://stackoverflow.com/questions/3408985/json-array-iteration-in-android-java) –

回答

4

遍歷JsonArray使用size同時使用get功能使用i指數,並將其轉換獲取的JsonElementJsonObject使用getAsJsonObject()功能

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); 
    } 

輸出:

0 
Noteeeeeeee 
John 
1 
Noteeeeeeee 
Rob