How to deserialize a class with overloaded constructors using JsonCreator

后端 未结 4 1422
挽巷
挽巷 2020-12-08 18:24
4条回答
  •  情话喂你
    2020-12-08 18:34

    If I got right what you are trying to achieve, you can solve it without a constructor overload.

    If you just want to put null values in the attributes not present in a JSON or a Map you can do the following:

    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Person {
        private String name;
        private Integer age;
        public static final Integer DEFAULT_AGE = 30;
    
        @JsonCreator
        public Person(
            @JsonProperty("name") String name,
            @JsonProperty("age") Integer age) 
            throws IllegalArgumentException {
            if(name == null)
                throw new IllegalArgumentException("Parameter name was not informed.");
            this.age = age == null ? DEFAULT_AGE : age;
            this.name = name;
        }
    }
    

    That was my case when I found your question. It took me some time to figure out how to solve it, maybe that's what you were tring to do. @Brice solution did not work for me.

提交回复
热议问题