GSON无法正确解析嵌套的JSON对象

时间:2019-03-03 20:00:02

标签: java android json parsing gson

我有一些JSON形式的数据,并且正在使用GSON库将其解析为一个Java对象,以在代码的后续部分中使用。 JSON具有嵌套的对象,这些对象似乎无法正确解析,而且我无法弄清楚原因,因为外部对象正在按需转换。这是我正在查看的JSON数据的示例:

{  
   "title":"Emergency Services Headquarters",
   "description":"",
   "cid":"C70856",
   "building_id":"4714",
   "building_number":"3542",
   "campus_code":"20",
   "campus_name":"Busch",
   "location":{  
      "name":"Emergency Services Headquarters",
      "street":"129 DAVIDSON ROAD",
      "additional":"",
      "city":"Piscataway",
      "state":"New Jersey",
      "state_abbr":"NJ",
      "postal_code":"08854-8064",
      "country":"United States",
      "country_abbr":"US",
      "latitude":"40.526306",
      "longitude":"-74.461470"
   },
   "offices":[  
      "Emergency Services"
   ]
}

我使用codebeautify创建了JSON所需的Java对象类(所有内容都在Building.java中):

public class Building {
    private String title;
    private String description;
    private String cid;
    private String building_id;
    private String building_number;
    private String campus_code;
    private String campus_name;
    Location LocationObject;
    ArrayList < Object > offices = new ArrayList < Object > ();

    //Setters and getters have been omitted

}

class Location {
    private String name;
    private String street;
    private String additional;
    private String city;
    private String state;
    private String state_abbr;
    private String postal_code;
    private String country;
    private String country_abbr;
    private String latitude;
    private String longitude;

    //Setters and getters have been omitted
}

这是我用来解析JSON的代码,其中变量json是该方法的输入参数:

Gson obj = new Gson();
JsonArray buildingsArray = new JsonArray();
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
buildingsArray = jsonElement.getAsJsonArray();
for (int i = 0; i < buildingsArray.size(); i++)
    Building building = obj.fromJson(buildingsArray.get(i), Building.class);

当我调用诸如building.getTitle()或building.getCid()之类的方法时,我会获得适当的值,但是当我进行building.getLocation()(其中Location是一个单独的对象)时,代码将返回null。我一直无法弄清楚,这与GSON的工作方式有关吗?还是我的代码做错了什么?

3 个答案:

答案 0 :(得分:3)

首先,更改:

Location LocationObject;

收件人:

private Location location;

而且,您可以更轻松地对JSON进行反序列化:

Gson gson = new GsonBuilder().create();
Building building = gson.fromJson(json, Building.class);

答案 1 :(得分:2)

Json属性名称应与您的POJO类属性匹配,它应该是location而不是LocationObject

public class Building {
private String title;
private String description;
private String cid;
private String building_id;
private String building_number;
private String campus_code;
private String campus_name;
Location location;
ArrayList < Object > offices = new ArrayList < Object > ();

//Setters and getters have been omitted

}

答案 2 :(得分:1)

似乎您的命名不正确。当您将JSON中的对象称为LocationObject时,您在Building类中的位置对象称为location