How to tell Jackson to ignore empty object during deserialization?

后端 未结 3 2058
遥遥无期
遥遥无期 2020-12-06 06:40

At the deserialization process (which as I understand is the process of converting JSON data into a Java Object), how can I tell Jackson that when it reads a object that con

3条回答
  •  不知归路
    2020-12-06 07:04

    I would use a JsonDeserializer. Inspect the field in question, determine, if it is emtpy and return null, so your ContainedObject would be null.

    Something like this (semi-pseudo):

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

    then in your model:

     public class Entity {
        private long id;
        private String description;
    
        @JsonDeserialize(using = MyDes.class)
        private ContainedObject containedObject;
    
       //Contructor, getters and setters omitted
    
     }
    

    Hope this helps!

提交回复
热议问题