Consider a case like below. I want to serialize ClassA object s.t. I use different object mapper properties for bObject
and cObject
class ClassA {
ClassB bObject = new ClassB();
ClassC cObject = new ClassC();
}
class ClassB {
ClassD dObject = new ClassD();
}
class ClassC {
ClassD dObject = new ClassD();
}
class ClassD {
int firstMember = 1;
String second_member = "Two";
}
void test() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
objectMapper.writerWithDefaultPrettyPrinter();
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(new ClassA()));
}
e.g. I want to use PropertyNamingStrategy.UPPER_CAMEL_CASE
for bObject
and PropertyNamingStrategy.SNAKE_CASE
for cObject
The serialized json should look like :
{
"bObject" : {
"dObject" : {
"firstMember" : 1,
"secondMember" : "Two"
.... similarly camel case for any nested ....
}
},
"cObject" : {
"d_object" : {
"first_member" : 1,
"second_member" : "Two"
.... similarly snake case for any nested ....
}
}
}
I've tried adding @JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)
& @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
to ClassB
and ClassC
respectively . That fixes the name for dObject
but not for the fields within it.
Any suggestions ? If I could use Mix-ins or custom serializer & deserializer ?
Context on why I need to do so : My current POJO is classA
which uses classB
and used at our service boundaries and is being serialized with a certain config. We're now adding ClassC
(not owned by us) to POJO. Serializers/Derserialzer for classC
need to follow a different convention.