Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change field case with an ObjectMapper

Tags:

I think I need to create a specialist ObjectMapper and cannot find any sample code to start the process.

The creator of the JSON is using .Net and public properties and therefore uses field names with an uppercase initial. I am parsing the JSON into POJOs so I would like to use a lowercase initial.

At their end:

    public class Facet     {         public string Name { get; set; }         public string  Value { get; set; }     } 

At my end I must therefore have:

    public class Facet {         public String Name;         public String Value;     } 

I would much prefer:

    public class Facet {         public String name;         public String value;     } 

Am I right that this could be done with an ObjectMapper?

like image 631
OldCurmudgeon Avatar asked Sep 14 '12 15:09

OldCurmudgeon


People also ask

Should I declare Jackson's ObjectMapper as a static field?

Yes, that is safe and recommended.

What is the use of ObjectMapper in Java?

ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode ), as well as related functionality for performing conversions.

What is ObjectMapper readValue in Java?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.


1 Answers

Your first issue can be addressed very simply with the @JsonProperty annotation:

// java-side class public class Facet {     @JsonProperty("Name")     public String name;      @JsonProperty("Value")     public String value; } 

Now the ObjectMapper will match up the differently-cased field names. If you don't want to add annotations into your classes, you can create a Mix-in class to stand in for your Facet:

public class FacetMixIn {     @JsonProperty("Name")     public String name;      @JsonProperty("Value")     public String value; }  objectMapper.getDeserializationConfig().addMixInAnnotations(Facet.class, FacetMixIn.class); 

This will achieve the same thing, without requiring additional annotations in your Facet class.

like image 60
pb2q Avatar answered Sep 18 '22 12:09

pb2q