Inherit a model with different JSON property names

I have a class, say Person, that I want to populate from JSON using Jackson, but the property names vary depending on the source. Here's what the code currently looks like:

class Person {
    protected String firstName;
    protected String lastName;
    protected String address;

    public abstract void setFirstName(String firstName);
    public abstract void setLastName(String lastName);
    public abstract void setAddress(String address);

    // getters etc.
}

class PersonFormat1 extends Person {
    @Override
    @JsonProperty("firstName")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Override
    @JsonProperty("lastName")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override("address")
    public void setAddress(String address) {
        this.address = address;
    }
}

class PersonFormat2 extends Person {
    @Override
    @JsonProperty("fName")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Override
    @JsonProperty("lName")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override("addr")
    public void setAddress(String address) {
        this.address = address;
    }
}

As you can see, PersonFormat1they are PersonFormat2identical in structure, but I need different subclasses to indicate different property names.

Is there a way to force the use of a model without a pattern of the need to reuse and override each method?

-3
source share
1 answer

One way is to use PropertyNamingStrategy http://wiki.fasterxml.com/PropertyNamingStrategy

, PropertyNamingStrategy


MixInAnnotations http://wiki.fasterxml.com/JacksonMixInAnnotations

MixInAnnotations Person Mixin .

public static void main(String[] args) throws IOException {
    ObjectMapper mapper1 = new ObjectMapper();
    String person1 = "{\"firstName\":null,\"lastName\":null,\"address\":null}";
    Person deserialized1 = mapper1.readValue(person1,Person.class);

    ObjectMapper mapper2 = new ObjectMapper();
    mapper2.addMixIn(Person.class, PersonMixin.class);
    String person2 = "{\"fName\":null,\"lName\":null,\"addr\":null}";
    Person deserialized2 = mapper2.readValue(person2,Person.class);
}

public static class Person {
    @JsonProperty("firstName")
    String firstName;
    @JsonProperty("lastName")
    String lastName;
    @JsonProperty("address")
    String address;

}

public class PersonMixin {
    @JsonProperty("fName")
    String firstName;
    @JsonProperty("lName")
    String lastName;
    @JsonProperty("addr")
    String address;
}
+1

Source: https://habr.com/ru/post/1649478/


All Articles