1. 程式人生 > >springmvc配置MappingJackson2HttpMessageConverter實現屬性駝峰和下劃線的轉換

springmvc配置MappingJackson2HttpMessageConverter實現屬性駝峰和下劃線的轉換

v需求

  php呼叫java介面時,因為php那邊的屬性都是下劃線風格,java這邊的屬性都是駝峰的風格。配置springmvc的json轉換,在requestBody的時候(呼叫物件的set 方法)將java屬性name對映成下劃線形式 和 請求的引數匹配;在responseBody的時候(呼叫物件的get方法)將java的屬性name也對映成下劃線形式。

vMappingJackson2HttpMessageConverter配置

<mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                        <!-- 處理responseBody 裡面日期型別 -->
                        <!--   <property name="dateFormat">
                              <bean class="java.text.SimpleDateFormat">
                                  <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />
                              </bean>
                          </property>  -->
                        <!-- 為null欄位時不顯示 -->
                        <property name="serializationInclusion">
                            <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                        </property>
                        <property name="propertyNamingStrategy">
                            <!--<bean class="com.xxx.serializer.MyPropertyNamingStrategyBase" />-->
                            <bean class="com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy" />
                        </property>
                    </bean>
                </property>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json; charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

v 自定義PropertyNamingStrategy

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by hujunzheng on 2017/6/7.
 */
public class MyPropertyNamingStrategyBase extends PropertyNamingStrategy {

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

    @Override
    public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return underscoreName(defaultName);
    }

    @Override
    public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
        return underscoreName(defaultName);
    }

    @Override
    public String nameForConstructorParameter(MapperConfig<?> config, AnnotatedParameter ctorParam,
                                              String defaultName) {
        return defaultName;
    }

    private String underscoreName(String name) {
        if (StringUtils.isEmpty(name)) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        result.append(name.substring(0, 1).toLowerCase());
        for (int i = 1; i < name.length(); ++i) {
            String s = name.substring(i, i + 1);
            String slc = s.toLowerCase();
            if (!(s.equals(slc))) {
                result.append("_").append(slc);
            } else {
                result.append(s);
            }
        }
        return result.toString();
    }

    private String withoutUnderscoreName(String name) {
        if (StringUtils.isEmpty(name)) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        result.append(name.substring(0, 1).toLowerCase());
        boolean underscore = false;
        for (int i = 1; i < name.length(); ++i) {
            String s = name.substring(i, i + 1);
            if ("_".equals(s)) {
                underscore = true;
                continue;
            } else {
                if (underscore) s = s.toUpperCase();
                underscore = false;
            }
            result.append(s);
        }
        return result.toString();
    }
}