2012-06-25 79 views
0

可能重複:
JSON Parsing in Android解析JSON在Android的

當我發現我需要使用GSON類來解析JSON到Java對象的機器人。這是很容易解析簡單varables或數組,但我不知道如何分析更復雜的JSON字符串,我的JSON是這樣的:

{"selected_id":3, "data":[{"id":"3","score":"1534"},{"id":"1","score":"1234"}]} 

誰能幫助我如何做到這一點?

+0

記住,{}是一個JSONObjects,和[]是JSONArrays。這只是瞭解JSON結構,然後從中提取不同的數組/對象。 – DecodeGnome

+0

我使用這個格柵[教程](http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html)學習如何與Gson合作,希望它也能幫助你: - ) –

回答

1
 //Model class 

    class Model { 

     private String mId ; 
      private String mScore; 

     public Model (String id , String score){ 

      mId = id ; 
      mScore= score 
     } 


     //getter and setter 

    } 

//你的班上

private ArrayLsit getLsit(String str){ 
     ArrayLsit<Model > list = new ArrayLsit<Model>(); 

     // getting JSON string from URL 
     JSONObject json = new JSONObject(str); 

     try { 
      // Getting Array of Contacts 
      contacts = json.getJSONArray("data"); 

      // looping through All Contacts 
      for(int i = 0; i < contacts.length(); i++){ 
       JSONObject c = contacts.getJSONObject(i); 

       // Storing each json item in variable 
       String id = c.getString("id"); 
       String score= c.getString("score"); 
       list.add(new Model(id ,score)) 

      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

    return list 

} 
+0

非常感謝,作品很棒:) – krinn

+0

Always Welcome ........ :) –

0

退房的代碼..

 Result = jsonObject.getString("data"); 

     jsonArray = new JSONArray(Result); 
     for (int i = 0; i < jsonArray.length(); i++) { 
      jsonObject = jsonArray.getJSONObject(i); 
      try { 
       jsonObject.getString("Id"); 

      } catch (Exception ex) { 
       cafeandbarsList.add(null); 
       ex.printStackTrace(); 
      } 
     } 

感謝

0

創造類JSON,

GSON GSON =新的Gson(); Jsondata jsonddata = gson.fromJson(response,Jsondata .class);

===== JsonData.jave

@SerializedName("selected_id") 
public String sid; 

    @SerializedName("data") 
public List<data> dalalist; 

=== data.java

@SerializedName("id") 
public String id; 

    @SerializedName("score") 
public String score;