How to deserialize a class with overloaded constructors using JsonCreator

后端 未结 4 1413
挽巷
挽巷 2020-12-08 18:24
4条回答
  •  粉色の甜心
    2020-12-08 18:48

    If you don't mind doing a little more work, you can deserialize the entity manually:

    @JsonDeserialize(using = Person.Deserializer.class)
    public class Person {
    
        public Person(@JsonProperty("name") String name,
                @JsonProperty("age") int age) {
            // ... person with both name and age
        }
    
        public Person(@JsonProperty("name") String name) {
            // ... person with just a name
        }
    
        public static class Deserializer extends StdDeserializer {
            public Deserializer() {
                this(null);
            }
    
            Deserializer(Class vc) {
                super(vc);
            }
    
            @Override
            public Person deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
                JsonNode node = jp.getCodec().readTree(jp);
                if (node.has("name") && node.has("age")) {
                    String name = node.get("name").asText();
                    int age = node.get("age").asInt();
                    return new Person(name, age);
                } else if (node.has("name")) {
                    String name = node.get("name").asText();
                    return new Person("name");
                } else {
                    throw new RuntimeException("unable to parse");
                }
            }
        }
    }
    

提交回复
热议问题