Ram Bavireddi
Ram Bavireddi

Reputation: 1187

Spring boot jackson - deserializes Json with root name

I have the below Json

{
    "user": {
        "name": "Ram",
        "age": 27
    }
}

which I want to de-serialize into an instance of the class

public class User {
    private String name;
    private int age;

    // getters & setters
}

For this, I have used @JsonRootName on class name and something like below

@Configuration
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.featuresToEnable(DeserializationFeature.UNWRAP_ROOT_VALUE);
        return builder;
    }
}

But it did not work as expected. If I send something like below, it worked.

{
 "name": "Ram",
 "age": 27
}

But I want to get the json de-serialized with root name. Can any one please suggest?

I want to spring boot way of doing this.

Upvotes: 5

Views: 9207

Answers (2)

Dash
Dash

Reputation: 9

Using ObjectMapper you can resolve this issue easily. Here's what you have to do : - Annotate User class as given below

@JsonRootName("user")
    public class User {
    private String name;
    private int age;

        // getters & setters
    }
  • Create CustomJsonMapper class

    public class CustomJsonMapper extends ObjectMapper {
    
        private DeserializationFeature deserializationFeature;
    
        public void setDeserializationFeature (DeserializationFeature  deserializationFeature) {
            this.deserializationFeature = deserializationFeature;
            enable(this.deserializationFeature);
        }
    }
    
  • Equivalent Spring configuration

    <bean id="objectMapper" class=" com.cognizant.tranzform.notification.constant.CustomJsonMapper">
        <property name="deserializationFeature" ref="deserializationFeature"/>
    </bean>
    <bean id="deserializationFeature" class="com.fasterxml.jackson.databind.DeserializationFeature"
          factory-method="valueOf">
        <constructor-arg>
            <value>UNWRAP_ROOT_VALUE</value>
        </constructor-arg>
    </bean>
    
  • Using following code you can test

    ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        ObjectMapper objectMapper = (ObjectMapper) context
                .getBean("objectMapper");
        String json = "{\"user\":{ \"name\": \"Ram\",\"age\": 27}}";
        User user = objectMapper.readValue(json, User.class);
    

Upvotes: -1

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

@JsonRootName is a good start. Use this annotation on User class and then enable UNWRAP_ROOT_VALUE deserialization feature by adding:

spring.jackson.deserialization.UNWRAP_ROOT_VALUE=true

to your application.properties. Read more about customizing Jackson mapper in Spring Boot Reference

Upvotes: 2

Related Questions