2013-04-06 104 views
1

如何使用谷歌Gson解析Json響應。與GSon嵌套的Json解析

{ 
    "rootobject":[ 
     { 
     "id":"7", 
     "name":"PP-1", 
     "subtitle":"name-I", 
     "key1":"punjab", 
     "key12":"2013", 
     "location":"", 
     "key13":"0", 
     "key14":"0", 
     "key15":"0", 
     "result_status":null 
     }, 
     { 
     "id":"7", 
     "name":"PP-1", 
     "subtitle":"name-I", 
     "key1":"punjab", 
     "key12":"2013", 
     "location":"", 
     "key13":"0", 
     "key14":"0", 
     "key15":"0", 
     "result_status":null 
     }, 
     { 
     "id":"7", 
     "name":"PP-1", 
     "subtitle":"name-I", 
     "key1":"punjab", 
     "key12":"2013", 
     "location":"", 
     "key13":"0", 
     "key14":"0", 
     "key15":"0", 
     "result_status":null 
     }, 
     { 
     "id":"7", 
     "name":"PP-1", 
     "subtitle":"name-I", 
     "key1":"punjab", 
     "key12":"2013", 
     "location":"", 
     "key13":"0", 
     "key14":"0", 
     "key15":"0", 
     "result_status":null 
     } 
    ] 
} 

回答

5

我想創建對象「包裝」的反應,如:

public class Response { 

    @SerializedName("root_object") 
    private List<YourObject> rootObject; 

    //getter and setter 
} 


public class YourObject { 

    @SerializedName("id") 
    private String id; 
    @SerializedName("name") 
    private String name; 
    @SerializedName("subtitle") 
    private String subtitle; 
    //... other fields 

    //getters and setters 
} 

注:使用@SerializedName註釋遵循命名約定在Java屬性,而在JSON匹配的名字數據。

然後你只解析JSON與Reponse對象,像這樣:

String jsonString = "your json data..."; 
Gson gson = new Gson(); 
Response response = gson.fromJson(jsonString, Response.class); 

現在你可以使用getter和setter訪問您Response對象中的所有數據。

注意:您的Response對象可能用於解析不同的JSON響應。例如,您可以使用不包含idsubtitle字段的JSON響應,但您的Reponse對象也會解析響應,並且只需在此字段中輸入null。這樣,你只能使用一個Response類來解析所有可能的響應...

編輯:我沒有意識到Android標記,我在通常的Java程序中使用這種方法,我不確定它是否有效期爲Android ...

+0

但我正在逐漸對象列表..?我怎樣才能將其標註爲..? RootObject還包含對象列表。 – DroidEngineer 2013-04-06 16:47:26

+1

爲真。查看編輯的代碼。你只需要改變一個列表的字段... – MikO 2013-04-06 16:51:12

1

你可以試試這個,希望這將工作

// Getting Array 
JSONArray contacts = json.getJSONArray("rootobject"); 
SampleClass[] sample=new SampleClass[contacts.length](); 

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

     // Storing each json item in variable 
     sample[i].id = c.getString("id"); 
     sample[i].name = c.getString("name"); 
     sample[i].email = c.getString("subtitle"); 
     sample[i].address = c.getString("key1"); 
     sample[i].gender = c.getString("key12"); 
     sample[i].gender = c.getString("location"); 
     sample[i].gender = c.getString("key13"); 
     sample[i].gender = c.getString("key14"); 
     sample[i].gender = c.getString("key15"); 
     sample[i].gender = c.getString("result_status"); 
     } 
+0

這肯定會起作用,但它的方法太慢了。 – DroidEngineer 2013-04-06 16:49:00