如何告诉jackson在反序列化期间忽略空对象?
在反序列化过程中(我理解的是将JSON数据转换为Java对象的过程),如何告诉Jackson当它读取不包含数据的对象时,应该忽略它?
我正在使用Jackson 2.6.6和Spring 4.2.6
我的控制器收到的JSON数据如下:
{ "id": 2, "description": "A description", "containedObject": {} }
问题是对象“containsObject”被解释为is并且它正被实例化。 因此,只要我的控制器读取此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 }
我会使用JsonDeserializer
。 检查有问题的字段,确定它是否为emtpy
并返回null
,因此ContainedObject
将为null。
像这样的东西(半伪):
public class MyDes extends JsonDeserializer { @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 }
希望这可以帮助!
您可以按如下方式实现自定义反序列化器:
public class Entity { private long id; private String description; @JsonDeserialize(using = EmptyToNullObject.class) private ContainedObject containedObject; //Contructor, getters and setters omitted } public class EmptyToNullObject extends JsonDeserializer { public ContainedObject deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { JsonNode node = jp.getCodec().readTree(jp); long contObjId = (Long) ((LongNode) node.get("contObjId")).numberValue(); String aString = node.get("aString").asText(); if(aString.equals("") && contObjId == 0L) { return null; } else { return new ContainedObject(contObjId, aString); } } }
方法1:这主要用于此。 @JsonInclude用于排除具有空/ null /默认值的属性。根据您的要求使用@JsonInclude(JsonInclude.Include.NON_NULL)或@JsonInclude(JsonInclude.Include.NON_EMPTY)。
@JsonInclude(JsonInclude.Include.NON_NULL) public class Employee { private String empId; private String firstName; @JsonInclude(JsonInclude.Include.NON_NULL) private String lastName; private String address; private String emailId; }
有关jackson注释的更多信息: https : //github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations
方法2:GSON
使用GSON( https://code.google.com/p/google-gson/ )