使用Jackson反序列化JSON的问题

时间:2017-02-08 08:42:48

标签: java json jackson

我有这样的JSON

{"body":{"result":[{"crossStateId":1,"raceId":181564,"withOfficer":1,"documents":[{"indexed":0,"documentNumber":"zzz","isMain":1,"documentTypeId":6,"serverId":16,"countryId":327,"useDate":"2017-02-07T19:31:51.000+0000","documentSubTypeId":6,"crossId":5018177,"documentId":44973231,"personId":222,"infinity":0,"documentValid":"2023-08-25T20:00:00.000+0000"}],"directionId":2,"documentNumber":"sss","operatorUsername":"AIRPORT_84","crossDate":"2017-02-07T19:31:51.000+0000","serverId":16,"crossTypeId":1,"crossRegisterDate":"2017-02-07T19:31:52.818+0000","officerNote":"","children":[],"personNote":"","crossId":5018177,"workplaceId":82,"divisionId":2,"race":{"carriageContainer":0,"raceId":181564,"raceStateId":1,"directionId":2,"creatorId":415,"countryId":327,"transportIdByType":605,"raceDateTime":"2017-02-07T19:20:58.000+0000","raceNumber":"841 sss sss","creatorUsername":"AIRPORT_8","divisionId":2,"transportTypeId":3,"createDate":"2017-02-07T19:20:58.000+0000"},"syncState":0,"autos":[],"userId":491,"raceNumber":"841 sss sss","operatorNote":"","person":{"firstNameEn":"JUMBERI","indexed":1,"lastNameGe":"ჩოხელი","genderId":2,"personId":6027803,"personalNumber":"222","countryNameGe":"sss","birthDate":"1963-06-14T20:00:00.000+0000","lastNameEn":"sss","countryId":327,"firstNameGe":"sss"},"airplane":{"raceNumber":"841 sss sss","airCompanyId":1,"airplaneId":605,"airportId":5657,"bortNumber":"01","transportSubTypeId":78,"countryId":360},"underAge":0,"personId":6027803,"decisionId":22}],"total":8264},"errorCode":0}

我想将它反序列化为Java类,但我只对一些JSON字段感兴趣。无论如何这里是模型类:

public class Response implements Serializable {
    private Body body;
    private long errorCode;

}

public class Body implements Serializable {
    Result result[];
}

public class Result implements Serializable {

    private long crossStateId;
    private long raceId;

    private Person person;
    private Child children [];
    private Auto autos[];

}

但由于某种原因,我得到以下例外:

  

org.codehaus.jackson.map.exc.UnrecognizedPropertyException:   无法识别的字段“body”(类com.demo.Response),未标记为   可以忽略[来源:java.io.StringReader@6483f5ae;行:1,列:   10](通过参考链:com.demo.Response [“body”])

这是代码(JSON字符串被正确接收,格式与我最初提到的格式相同):

 String res = MainProgram.sendGet("someURL");

 ObjectMapper objectMapper = new ObjectMapper();
 Response ob = objectMapper.readValue(res, Response.class);

我将不胜感激。

2 个答案:

答案 0 :(得分:0)

您需要为字段创建getter和setter,并且应该在字段中添加注释。

注释:

@JsonProperty(value = "body")
private Body body;

执行上述操作之一将使其正常工作。

旁注:

您可以使用http://www.jsonschema2pojo.org/自动从json创建您的pojos。只需将其粘贴并下载,或使用其中一个插件即可。

答案 1 :(得分:0)

正如其他人所提到的,默认情况下private字段不会自动检测,因此:

  • 使用@JsonProperty
  • 注释字段
  • 添加setter
反序列化需要

但是,还有另一种可能性:您可以使用注释@JsonAutoDetect来更改所需的最低可见性,并在此处启用所有字段的发现。 或者您甚至可以通过ObjectMapper方法更改默认设置(类似setVisibility(...))。