嵌套的Json与GSON解析(Nested Json parsing with GSon)

2019-10-17 23:59发布

如何解析以下与谷歌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
      }
   ]
}

Answer 1:

我想创建对象“包装”的反应,如:

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);

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

注意:您的Response对象可以用来分析不同的JSON响应。 例如,你可以有不包含JSON响应idsubtitle领域,但你的Reponse对象将解析响应,以及,只是把null在这个领域。 这样你就可以只用一个Response类来分析所有可能的回应...

编辑:我不知道Android的标签,我用一个通常的Java程序这种做法,我不知道它是否是有效的为Android ...



Answer 2:

你可以试试这个希望这将工作

 // 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");
       }


文章来源: Nested Json parsing with GSon