coderatchet
coderatchet

Reputation: 8428

Customizing Field Name Serialization in Jackson Object Mapper

Say I have a bean:

public class MyBean {
    public String oneMississipi;
    public int myBestFriend;
    //Getters&Setters&Bears,Oh my.
}

And I am using com.fasterxml.Jackson DataBinding to transform instances of this pojo into json output... How do I customize the serialization of field names and can this be scoped to a global/class/field level?

e.g. I wish to dasherize my field names:

{
    "one-mississipi": "two mississippi",
    "my-best-friend": 42
}

I have already spent hours in Google and even trawling through the jackson code in order to find out where the field serialization occurs, but can't seem to see anywhere that it may delegate for custom field processing.

Does anyone have any ideas as to where this functionality lies if any? Much appreciated

Upvotes: 1

Views: 1166

Answers (1)

pingw33n
pingw33n

Reputation: 12510

Implement PropertyNamingStrategy and inside the resolving methods use AnnotatedMethod, AnnotatedField or AnnotatedParameter to get the declaring class. Then you can look for any custom annotation on that class and apply any custom naming depending on it.

The biggest problem with this approach is that it's not possible to get the actual concrete class being serialized or deserialized, it will always return the declaring class. So it won't be possible to override naming behavior in subtypes for the inherited members unless you bring them into the subtype.

Another solution would be using different mappers for classes that have different naming strategies. You can make it more or less transparent by creating a top-level "router" mapper that will decide which mapper instance to use (special care must be taken for configuration methods and other non ser/deser related methods). Assuming that you will have a finite number of the strategies this solution should be workable too.

The drawback of this solution is that you won't be able to mix different naming strategies during a single serialization / deserialization run.

Upvotes: 4

Related Questions