Spring boot jackson - deserializes Json with root name

主宰稳场 提交于 2021-01-27 12:52:48

问题


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.


回答1:


@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




回答2:


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);
    


来源:https://stackoverflow.com/questions/37236709/spring-boot-jackson-deserializes-json-with-root-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!