I have this JSON to deserialize:
{
\"first-name\": \"Alpha\",
\"last-name\": \"Beta\",
\"gender\": \"m\"
}
I want to serialize
There is a far easier way to do this - create an objectmapper that uses the "addMixin" function.
Class to be serialized:
Class YouWantToSerializeMe {
public String firstName;
public String lastName;
public String gender;
@JsonProperty("firstName")
public String getFirstNameCC() {
return firstName;
}
@JsonProperty("lastName")
public String getLastNameCC() {
return lastName;
}
}
Now, to serialize using both the built-in field names and custom field names, you can do this:
Class DoTheSerializing {
String serializeNormally(YouWantToSerializeMe me) {
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter objectWriter = objectMapper.writer();
return objectWriter(me)
}
String serializeWithMixin(YouWantToSerializeMe me) {
ObjectMapper objectMapper = new ObjectMapper();
ObjectWriter objectWriter = objectMapper
.addMixIn(YouWantToSerializeMe.class, MyMixin.class)
.writer();
return objectWriter(me)
}
interface MyMixin {
@JsonProperty("first-name")
public String getFirstNameCC();
@JsonProperty("last-name")
public String getLastNameCC();
}
}
This uses an embedded interface in the class to keep things very local. You can make lots of optimizations around this, such as creating a static ObjectMapper and loading/unloading the mixin.
Using the interface as a "template" to control the mapping function is really powerful. You can add things at both the field and class level.