1

如何使用谷歌 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
      }
   ]
}
4

2 回答 2

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 数据中的名称。

然后,您只需使用您的Reponse对象解析 JSON,如下所示:

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

现在您可以Response使用 getter 和 setter 访问对象中的所有数据。

注意:您的Response对象可用于解析不同的 JSON 响应。例如,您可能有不包含idorsubtitle字段的 JSON 响应,但您的Reponse对象也会解析响应,并且只需null在此字段中放入 a。这样你就可以只使用一个Response类来解析所有可能的响应......

编辑:我没有意识到Android标签,我在一个普通的Java程序中使用这种方法,我不确定它是否对Android有效......

于 2013-04-06T13:10:49.937 回答
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");
       }
于 2013-04-06T13:19:59.547 回答