如何使用google Gson在Json Response下解析。?
{
"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
}
]
}
答案 0 :(得分:5)
我创建对象" wrap"响应,例如:
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
对象也会解析响应,只需添加{{ 1}}在这个领域。这样,您只能使用一个null
类来解析所有可能的响应......
答案 1 :(得分: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");
}