JSON Property Name Customization in Jackson using PropertyNamingStrategy

Jackson is one of the most popular java libraries for serialization/deserialization of POJOs to/from JSON. By default, Jackson derives the JSON element names from the getter/setter method names of the POJO. e.g. getActorName() is translated to actorName in the resulting JSON.

Let's take the following POJO and serialization function for our examples.

//The POJO that needs to be serialized
public class Actor {
 private String actorName;
 private Gender actorGender;
 public Actor() {}
 public Actor(String name, Gender gender) {
  this.actorName = name; this.actorGender = gender;
 }
 public String getActorName() {
  return actorName;
 }
 public void setActorName(String actorName) {
  this.actorName = actorName;
 }
 public Gender getActorGender() {
  return actorGender;
 }
 public void setActorGender(Gender actorGender) {
  this.actorGender = actorGender;
 }
}

//Code that serializes the actor object to JSON
Actor actor = new Actor("Al Pacino", Gender.MALE);
ObjectMapper mapper = new ObjectMapper();
Writer w = new StringWriter();
mapper.writeValue(w, actor);
System.out.println(w.toString());

//The resulting JSON with default camelcase
{
 "actorName":"Al Pacino",
 "actorGender":"MALE"
}

Customizing element names


Jackson allows you to change this default behavior through PropertyNamingStrategy.
PropertyNamingStrategy provides a few template methods that can be overridden to derive custom element names from the method names (for serialization) and vice-versa (for deserialization).

nameForGetterMethod resolves the element names for the given getter method during serialization.
nameForSetterMethod identifies the element names for the given setter method during deserialization.

This strategy can then be set on the ObjectMapper, before reading or writing to it.

mapper.setPropertyNamingStrategy(myStrategyInstance);

Jackson Strategies


Jackson provides at least two Strategies out of the box.

LowerCaseWithUnderscoresStrategy - It converts camel case properties to lowercase element names separated by underscores. It's a private class and can't be used directly. Instead, it can be used in the following manner.
mapper.setPropertyNamingStrategy(
      PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);

//The resulting JSON with underscores
{
 "actor_name":"Al Pacino",
 "actor_gender":"MALE"
}

PascalCaseStrategy - It converts camel case properties to PascalCase element names.
mapper.setPropertyNamingStrategy(
      PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE);

//The resulting JSON with PascalCase elements
{
 "ActorName":"Al Pacino",
 "ActorGender":"MALE"
}


Custom strategies


You can also define a custom strategy of your own. The AllLowerCasePropertyNamingStrategy defined below converts the property names to lowercase element names. The defaultName here is the element name that the default strategy provides.

public class AllLowerCasePropertyNamingStrategy extends PropertyNamingStrategy {
     
    @Override
    public String nameForGetterMethod(MapperConfig config,
            AnnotatedMethod method, String defaultName) {
        return defaultName.toLowerCase();
    }

    @Override
    public String nameForSetterMethod(MapperConfig config,
            AnnotatedMethod method, String defaultName) {
        return defaultName.toLowerCase();
    }
    
}

mapper.setPropertyNamingStrategy(
      new AllLowerCasePropertyNamingStrategy());

//The resulting JSON with lowercase element names
{
 "actorname":"Al Pacino",
 "actorgender":"MALE"
}

Another example of a custom strategy, StripPrefixPropertyNamingStrategy, strips the given prefix from the property names to derive the element names.

private static class StripPrefixPropertyNamingStrategy extends PropertyNamingStrategy {

 private String prefix;

 public StripPrefixPropertyNamingStrategy(String prefix) {
  this.prefix = prefix;
 }

 @Override
 public String nameForGetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) {
  return defaultName.replaceFirst(prefix, "");
 }

 @Override
 public String nameForSetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName) {
  return defaultName.replaceFirst(prefix, "");
 }

}

mapper.setPropertyNamingStrategy(
      new StripPrefixPropertyNamingStrategy("actor"));

//The resulting JSON without the actor prefix
{
 "Name":"Al Pacino",
 "Gender":"MALE"
}


16 comments:

  1. I gotta favorite this website it seems very helpful . gibraltar property for sale

    ReplyDelete
  2. Before we bounce into building a monetary model, we ought to ask ourselves what drives the business that we are investigating. The appropriate response will have critical ramifications for how we develop the model. Stump Grinding Stockton

    ReplyDelete
  3. In our situation, we need to discover what sort of monetary return we can anticipate from a venture property given certain data about the speculation. This data would incorporate factors, for example, the price tag, pace of appreciation, the cost at which we can lease it out, the financing terms accessible front the property, and so forth. mall of Islamabad payment plan

    ReplyDelete
  4. Doing an Internet search for "tree removal service" can often yield an immediate list of local tree contractors. Tree Trimming Franklin

    ReplyDelete
  5. There is a note pack to know about this. I assume you scored some good points in the features as well. Faisal hills Islamabad

    ReplyDelete
  6. So, it is very important to hire a certified company offering tree services in your area. Below, you will come across with few important reasons to hire professional tree Removal Company. Stump Grinding Santa Ana, CA

    ReplyDelete
  7. For quite a while at this point, individuals have been attempting to call me to inquire as to whether it is as yet a smart thought to put resources into property in the United States? I have been purchasing properties in the United States for over 20 years as of now. blue world city

    ReplyDelete
  8. Incredible article distributed here by you. I have long been eager to adapt new things in relation to this topic, and there is no doubt that I have adapted new things today. blacktown driving school

    ReplyDelete
  9. I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often. phuket property

    ReplyDelete
  10. Many thanks ...... Because of Imarah Marketing I booked my own home in Islamabad No doubt, the best Property Dealer in Gulberg. I will recommend your service to everyone buying land in Islamabad!
    https://imarahmarketing.com/
    https://imarahmarketing.com/blue-world-city/
    https://imarahmarketing.com/park-view-city-islamabad/

    ReplyDelete
  11. Amazing and Helpful post. I really appreciated your work.Many thanks for your kind and efficient service for booking a plot in park view city and blue world city.I will definitely recommend Imarah real estate services to others in the future.
    https://imarahmarketing.com/
    https://imarahmarketing.com/blue-world-city/
    https://imarahmarketing.com/park-view-city-islamabad/

    ReplyDelete
  12. Im no expert, but I believe you just made an excellent point. You certainly fully understand what youre speaking about, and I can truly get behind that. house property survey

    ReplyDelete
  13. Tajarat strives to be Pakistan's biggest real estate developer ever, guaranteeing the highest international standards, prompt execution, and lifetime customer loyalty. For further detail visit park view city islamabad cda

    ReplyDelete
  14. As in any industry, not all experts are something very similar. Insulation Removal Tampa

    ReplyDelete
  15. I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business. https://propertydeveloper546225.blogspot.com/2021/09/actual-property-developer-actual.html

    ReplyDelete