使用Gson

时间:2017-06-20 06:30:44

标签: java android json gson

我希望从整个嵌套的json中获取列表json的一部分。我有一个json,如下所示:

{
  "response": 200,
  "responseMsg": "Allright",
  "location": [
    {
      "stateId": 1,
      "stateName": "West Bengal",
      "district": [
        {
          "districtId": 15,
          "districtName": "abc",
          "village": [
            {
              "villageId": 121,
              "villageName": "ABC"
            },
            {
              "villageId": 90,
              "villageName": "XYZ"
            }
          ]
        },
        {
          "districtId": 11,
          "districtName": "xyz",
          "village": [
            {
              "villageId": 58,
              "villageName": "PQR"
            }
          ]
        }
      ]
    }
  ]
}

我编写了如下bean文件: Details.java:

public class Details {

    private int response = 0;
    private String responseMsg = null;
    private List<State> states = null;
public List<State> getLocation() {
        return location;
    }  

State.java:

public class State {

    private int stateId = 0;

    private String stateName=null;

    private List<District> district;

    public List<District> getDistrict() {
        return district;
    }

现在,我只想让State json不同,以便我可以使用它作为List来填充android中的微调器。 为了解析json,我正在使用

Gson googleJson = builder.create();Details details = googleJson.fromJson(result, Details.class);               
List<State> stateList = details.getLocation();

但是当我再次使用gson.toJson(stateList)将其转换为json时,这会给出:

[
  {
    "district": [
      {
        "village": [
          {
            "villageName": "Mekhliganj",
            "villageId": 57
          }
        ],
        "districtName": "Cooch Bihar",
        "districtId": 10
      }
],"stateName=West Bengal","stateId":1
}
}

但是当我再次将其转换为json时,状态名称最终会出现这种情况。 此外,当我再次尝试将其解析为:

时,同样的json(stateList)会给出空指针异常
State stateObj = gson.fromJson(stateList,State.class);

这样做的正确方法是什么?即从一个整体使用gson获取json(list)的一部分并解析该部分?

2 个答案:

答案 0 :(得分:0)

为你找到解决方案......

您没有在下面的函数中传递整个响应

尝试以下步骤以获得完整的回复:

1)将数据存储在String或您正在存储的任何对象类中。

2)

Gson gson = new Gson();
   String string = gson.toJson(response);

注意:您只是解析剩余的响应。您没有解析原始响应。只需在解析上面的函数时重新检查响应就可以了解断点。

答案 1 :(得分:0)

public class Details {

    private int response = 0;
    private String responseMsg = null;
    private Location location = null;

    //add getter and setter

}

public class Location{
    private List<State>stateList;

//add getter and setter

}

最后

public class State {

    private int stateId = 0;
    private String stateName=null;
    private List<District> district;

    //add getter and setter
}