小编典典

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

spring

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

我正在使用Jackson 2.6.6和Spring 4.2.6

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

{
    "id": 2,
    "description": "A description",
    "containedObject": {}
}

问题是对象“ containedObject”按原样解释,并且正在实例化。因此,控制器读取此JSON数据后,它将立即生成ContainedObject对象类型的实例,但我需要将此实例设置为null。

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

 {
        "id": 2,
        "description": "A description",
        "containedObject": null
    }

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

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

我留下了我的班级的代表以获取更多信息:

我的实体类如下:

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

//Contructor, getters and setters omitted

}

我包含的对象类如下:

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

//Contructor, getters and setters omitted

}

阅读 2045

收藏
2020-04-21

共1个答案

小编典典

我会用一个JsonDeserializer。检查相关字段,确定是否为该字段emtpy并返回null,因此你ContainedObject将为null。

这样的东西(semi-pseudo):

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

    }

然后在你的模型中:

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

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

   //Contructor, getters and setters omitted

 }

希望这可以帮助!

2020-04-21