简体   繁体   中英

How to deserialize extended class using Jackson

In given class Base which is extended by Ext class. Serialization works perfect but issue is when trying to deserialize the serialized string back to Ext class. I want to deserialize back to Ext class including the all the Base class properties.

@Data, @NonFinal, @Value are all lombok annotations.

@Data
public class Base {

    private String foo;

    public Base( String foo) {
        this.foo = foo;
    }
}
@Value
@NonFinal
public class Ext extends Base  {

    private String bar;

    public Ext(String foo,  String bar) {
        super(foo);
        this.bar = bar;
    }

}

Method to Deserialize

    @Test
    void shouldDeserialize() throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        Ext ext = new Ext("foo", "bar");

        String serializedExt = mapper.writeValueAsString(ext);
        System.out.println(serializedExt); // {"foo":"foo","bar":"bar"}
        
        // Throws err
        base = mapper.readValue(serializedExt, Ext.class);
        
    }

Error: com.fasterxml.jackson.databind.exc.InvalidDefinitionException:Cannot construct instance of..Inhertence.Ext(no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (String)"{"foo":"foo","bar":"bar"}"; line: 1, column: 2] com.fasterxml.jackson.databind.exc.InvalidDefinitionException:Cannot construct instance of..Inhertence.Ext(no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (String)"{"foo":"foo","bar":"bar"}"; line: 1, column: 2]

The error message is indicative: in your class the default constructor is not present and you haven't annotated its constructor with the JsonCreator annotation. You can deserialize your class annotating its constructor:

@Value
@NonFinal
public class Ext extends Base {

    private String bar;

    @JsonCreator
    public Ext(@JsonProperty("foo") String foo, @JsonProperty("bar") String bar) {
        super(foo);
        this.bar = bar;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM