与GSon嵌套的Json解析
问题描述:
如何使用谷歌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
}
]
}
答
我想创建对象“包装”的反应,如:
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响应。例如,您可以使用不包含id
或subtitle
字段的JSON响应,但您的Reponse
对象也会解析响应,并且只需在此字段中输入null
。这样,你只能使用一个Response
类来解析所有可能的响应...
编辑:我没有意识到Android标记,我在通常的Java程序中使用这种方法,我不确定它是否有效期为Android ...
答
你可以试试这个,希望这将工作
// 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
但我正在逐渐对象列表..?我怎样才能将其标注为..? RootObject还包含对象列表。 – DroidEngineer 2013-04-06 16:47:26
为真。查看编辑的代码。你只需要改变一个列表的字段... – MikO 2013-04-06 16:51:12