在反序列化过程(据我所知是将 JSON 数据转换为 Java 对象的过程),我如何告诉 Jackson 当它读取一个不包含数据的对象时,它应该被忽略?
我正在使用 Jackson 2.6.6 和 Spring 4.2.6
我的 Controller 接收到的JSON数据如下:
{
"id": 2,
"description": "A description",
"containedObject": {}
}
问题是对象“containedObject”被解释为原样并且正在被实例化。因此,只要我的 Controller 读取此 JSON 数据,它就会生成一个 ContainedObject 对象类型的实例,但我需要将其设为 null。
最简单和最快的解决方案是在接收到的 JSON 数据中,这个值为 null,如下所示:
{
"id": 2,
"description": "A description",
"containedObject": null
}
但这是不可能的,因为我无法控制发送给我的 JSON 数据。
是否有一个注释( like this explained here )适用于反序列化过程并且对我的情况有帮助?
我留下了我的类(class)的代表以获取更多信息:
我的实体类如下:
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
}
最佳答案
我会使用 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;
}
}
然后在你的模型中:
public class Entity {
private long id;
private String description;
@JsonDeserialize(using = MyDes.class)
private ContainedObject containedObject;
//Contructor, getters and setters omitted
}
希望这可以帮助!
关于java - 如何告诉 jackson 在反序列化期间忽略空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40366524/