Skip to main content

Customizing Root Node Name in Jackson JSON Processor - JAXB Route

By default, Jackson JSON processor does not wrap the JSON object with the root name when used with JaxB Introspection(@JsonRootName will work for non-JaxB implementation). You can enable this feature by setting the property SerializationConfig.Feature.WRAP_ROOT_VALUE and DeserializationConfig.Feature.UNWRAP_ROOT_VALUE to true.

Domain Object - User.java

@XmlType(name = "user")
public class User implements Serializable {

    @XmlElement(name = "first_name")
    protected String firstName;

    @XmlElement(name = "last_name")
    protected String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String value) {
        this.firstName = value;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String value) {
        this.lastName = value;
    }
}
Default Jackson generated JSON Output
{"first_name": "James", "last_name": "Gosling"}
With WRAP_ROOT_VALUE=true
{"User": {"first_name": "James", "last_name": "Gosling"} }
All good? Not yet. Noticed the naming convention used in the root node? It came out in Pascal case(begins with a capital letter), how? By default Jackson uses class name as the root name. This makes our JSON output ugly. Let us find a way to make this root name inline with our naming convention.

JaxbAnnotationIntrospector for your rescue

We can tell Jackson ObjectMapper to use JAXB annotations to map objects with name and change the behavior of name generation by providing a customized version of JaxbAnnotationIntrospector. We can use this class to change the root name or even the property names; change to lower case, change to upper case, suffix or prefix names with custom string or even give new name to the elements.

Name root element as defined in JaxB

Below class overrides findRootName() of JaxbAnnotationIntrospector and returns the XmlType as root name.
public class MyAnnotationIntrospector extends JaxbAnnotationIntrospector {
 @Override
 public String findRootName(AnnotatedClass ac) {

  return ac.getAnnotations().get(XmlType.class).name();
 }
}
If you want to do it for only specific domain objects, you can add the below condition:
 if(ac.getAnnotated().getName().equalsIgnoreCase("com.texient.domain.User")) {...}
Now you can use this introspector in the mapper object:
public class MyObjectMapperFactory {

    public static ObjectMapper createMapper() {

        final ObjectMapper mapper = new ObjectMapper(); 
        final JaxbAnnotationIntrospector myAnnotationIntrospector = new MyAnnotationIntrospector();

        final DeserializationConfig deserializeConf = mapper.getDeserializationConfig()  
                .with(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE)
                .withAnnotationIntrospector(myAnnotationIntrospector);

        mapper.setDeserializationConfig(deserializeConf);

        final SerializationConfig serializeConf = mapper.getSerializationConfig()
                .with(SerializationConfig.Feature.WRAP_ROOT_VALUE)
                .withSerializationInclusion(JsonSerialize.Inclusion.NON_NULL)
                .withAnnotationIntrospector(myAnnotationIntrospector);

        mapper.setSerializationConfig(serializeConf);

        return mapper;
    }
}

Conclusion

So, with a custom Annotation Introspector you can customize the way the JSON serialization and de-serialization are done. Feel free to drop your feedback below.

Comments

  1. This blog tries to prevent copying and pasting of example code in a (not very effective) rude manner. What's the point of posting this if you don't want anyone to use these snippets?

    There is no more setSerializationConfig (in Jackson 2.4.1 at least), you can simply use mapper.setAnnotationIntrospector(…).

    ReplyDelete
    Replies
    1. Don't copy+paste, understand the concept and then implement it on your own :) You are right, setSerializationConfig() is available only in older versions, i think below 2.0 versions, which has package org.codehaus.jackson.* not with com.fasterxml.jackson.*.

      Delete

Post a Comment

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to our feed and get articles like this delivered automatically to your feed reader? Like our Facebook Page.

Popular posts from this blog

HDFC Bank introduces Missed Call Service to know Account Balance

Missed call is a powerful business tool in developing countries like India where customers give a miss call to specific phone numbers for getting account details, providing feedback, voting etc. On receiving a missed call from a registered phone number, the underlying app performs a phone number lookup and sends the data to the caller via text message(SMS) or records the call details for future processing.HDFC Bank recently introduced missed call service for its retail customers which allows to retrieve bank account details, mini statement etc. by simply giving a miss call to their toll free numbers.Following services are now available: 1800 270 3333 - Account Balance 1800 270 3355 - Mini Statement 1800 270 3366 - Request for new Cheque Book 1800 270 3377 - Request for Bank account statement Also you can download HDFC Mobile Banking Application by giving a missed call to : 1800 270 3344. Other banks providing missed call serviceAxis bank(known as Axis Dial) - 09225892258Bank of India…

Induction Cooker Showing an Error Code? Induction Cooker Error Codes Explained

Are you searching for Induction Cook-top error codes? Here you can find the error codes of all popular induction cooktops and how to troubleshoot it.

These are for your reference only, do not try to open your cooktop without proper safety measures, we advise you to call the service person if any servicing is needed.

If you want to know how Induction Cook-top works, read our previous article titled What is Induction Cooker? How Induction Cooker Works?.

Whirlpool Induction Cooker Error CodesError CodeErrorSolutionF0An internal error was detected.Disconnect power. Wait 5 seconds before reconnecting power. If the symbol appears again, call for service.F2The surface cooking area is too hot and has turned off.Remove the pans from the surface cooking area. "F2" will disappear when the surface cooking area has cooled. If you turn the surface cooking area back on and "F2" reappears, the cooktop is still too hot. Turn off the surface cooking area and allow it to cool.F4The po…

LICHFL - Generating Home Loan Statements Online

Generating an online statement from LIC Housing Finance Ltd is very easy, simply follow the below steps to create an online account with LICHFL and generate statements online! You may use the online generated statement as a proof for principal paid for a housing loan(under section 80C) and interest paid(under section 24) while filing income tax returns.Want to know how to save maximum income tax? Read our most read article how to save maximum income tax(opens in new tab).Before reading further, make sure you have the following information with you: Your Loan Account NumberSanctioned AmountStep 1 - Open LICHFL websiteVisit LICHFL website and click on the 'New Customers? Click Here' link(refer the below screenshot). Step 2 - Enter your loan account detailsFill in the following details: New Loan NumberSanctioned AmountDate of BirthSecurity Codeand click on the Submit button. Step 3 - Enter your personal detailsEnter your email address, a username and password and click on submi…