如何告诉杰克逊在反序列化期间忽略空对象?

Mau*_*ner 6 java spring json jackson

在反序列化过程中(据我所知是将JSON数据转换为Java对象的过程),如何告诉Jackson当它读取不包含数据的对象时,应该忽略它?

我正在使用Jackson 2.6.6和Spring 4.2.6

我的控制器收到的JSON数据如下:

{
    "id": 2,
    "description": "A description",
    "containedObject": {}
}
Run Code Online (Sandbox Code Playgroud)

问题是对象"containedObject"被解释为is并且它正被实例化.因此,只要我的控制器读取此JSON数据,它就会生成ContainedObject对象类型的实例,但我需要将其替换为null.

最简单,最快速的解决方案是,在收到的JSON数据中,此值为null,如下所示:

 {
        "id": 2,
        "description": "A description",
        "containedObject": null
    }
Run Code Online (Sandbox Code Playgroud)

但这是不可能的,因为我无法控制发送给我的JSON数据.

是否有一个注释(如此处所解释的)适用于反序列化过程,可能对我的情况有所帮助?

我留下了我的课程表示以获取更多信息:

我的实体类如下:

public class Entity {
    private long id;
    private String description;
    private ContainedObject containedObject;

//Contructor, getters and setters omitted

}
Run Code Online (Sandbox Code Playgroud)

我的包含对象类如下:

public class ContainedObject {
    private long contObjId;
    private String aString;

//Contructor, getters and setters omitted

}
Run Code Online (Sandbox Code Playgroud)

Mec*_*kov 7

我会用一个JsonDeserializer.检查有问题的字段,确定是否emtpy返回null,这样你ContainedObject就会为空.

像这样的东西(半伪):

 public class MyDes extends JsonDeserializer<ContainedObject> {

        @Override
        public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
            //read the JsonNode and determine if it is empty JSON object
            //and if so return null

            if (node is empty....) {
                return null;
            }
            return node;
        }

    }
Run Code Online (Sandbox Code Playgroud)

然后在你的模型中:

 public class Entity {
    private long id;
    private String description;

    @JsonDeserialize(using = MyDes.class)
    private ContainedObject containedObject;

   //Contructor, getters and setters omitted

 }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!