如何用google 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
}
]
}发布于 2013-04-06 21:10:50
我会创建对象来“包装”响应,比如:
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数据中的名称。
然后,您只需使用Reponse对象解析JSON,如下所示:
String jsonString = "your json data...";
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);现在,您可以使用getter和setter访问Response对象中的所有数据。
注意:您的Response对象可用于解析不同的JSON响应。例如,您可以使用不包含id或subtitle字段的JSON响应,但是您的Reponse对象也将解析该响应,并且只需在这些字段中添加一个null。这样,您就可以只使用一个Response类来解析所有可能的响应……
编辑:我没有意识到Android标签,我在通常的Java程序中使用这种方法,我不确定它是否适用于Android……
发布于 2013-04-06 21:20:00
你可以试试这个,希望这能行得通
// 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");
}https://stackoverflow.com/questions/15851190
复制相似问题