How to [de]serialize to pojo objects from JSON when there is mixed camel case in names

790 views Asked by At

I'm using Dropwizard (which uses Jackson under the hood) to create a bridging API service. It connects to two other API's that are very similar (API1 and API2).

I have my own POJO library that contains the request and response POJO's for API1 and API2. The only difference between those two API's is that for certain objects API1 emits capitalised keys, whereas the other doesn't. Basically one API1 is implemented in Java and API2 is implemented in .NET but both serve the same data.

{
    "Name" : "foo",
    "Address" : "bar"
}

versus

{
    "name" : "foo",
    "address" : "bar"
}

I want to avoid writing a POJO class for each one when otherwise they are identical objects.

What is the correct way to tell Jackson to accept either name?

I'm aware of @JsonProperty e.g.

@JsonProperty("Name")
private String name;

However even if this works for both "name" and "Name", it feels a bit untidy. To me, declaring this annotation should effectively mean ignore the coded field name in favour of the annotation.

Thanks in advance

1

There are 1 answers

0
Dragan Bozanovic On BEST ANSWER

You may take a look at PropertyNamingStrategy which you can define for the ObjectMapper in use.

You could define different strategies for different service consumers (when you are the producer) if the other side is not flexible regarding the convention used (does not accept both upper- and lowercase forms).

If you can afford to use Jackson 2.5, then you could take a look at mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)

For full control over Jackson (de)serialization process, take a loot at custom serialization and custom deserialization.