Custom ObjectMapper and NamingStrategy in Spring 3 MVC

I'm using Spring MVC 3 and MappingJacksonHttpMessageConverter in order to get the json data with @ResponseBody. With the default config works ok but now i need to transform the camelCase fields to Pascal casing. For this purpose, i've developed a custom naming strategy:

UpperCaseNamingStrategy.java

public class UpperCaseNamingStrategy extends PropertyNamingStrategy {

    @Override
    public String nameForField(MapperConfig config, AnnotatedField field, String defaultName){
        return convert(defaultName);
    }

    @Override
    public String nameForGetterMethod(MapperConfig config, AnnotatedMethod method, String defaultName){
        return convert(defaultName);
    }

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

    public String convert(String defaultName){
        char[] arr= defaultName.toCharArray();
        if(arr.length != 0){
            if(Character.isLowerCase(arr[0])){
                arr[0] = Character.toUpperCase(arr[0]);
            }
        }
        return new StringBuilder().append(arr).toString();
    }
}

I set my custom strategy to the objectMapper and i set the objectMapper in the converter. These are the beans:

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="objectMapper" ref="jacksonObjectMapper" />
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
        <ref bean="jacksonMessageConverter"/>
        </list>
    </property>
</bean>

<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
    <property name="propertyNamingStrategy" ref="namingStrategy"/>
</bean>

<bean id="namingStrategy" class="es.unican.meteo.util.UpperCaseNamingStrategy"></bean>

The beans are registered properly because i can see it in the log but when i request the json data the behaviour is the same and the converter method is not called. Do I need more configs?


Following changes are suggested as compared to what I did in my project:

  • Change mapper bean class to "com.fasterxml.jackson.databind.ObjectMapper". I am using Spring 4.3
  • add @JsonProperty annotation to the property of class which is being serielized/deseralized
  • Create default constructors in class which is being serielized/deseralized
  • Best of Luck!

    链接地址: http://www.djcxy.com/p/48814.html

    上一篇: 为什么当我使用hibernate时,这个类应该实现java.io.Serializable?

    下一篇: Spring 3 MVC中的自定义ObjectMapper和NamingStrategy