Fastjson: 属性名相同,其中一个带下划线,数据类型不同,反序列化报错

Created on 7 Sep 2017  ·  2Comments  ·  Source: alibaba/fastjson

有这样一个类

public class Model {
    private Integer id;
    private String branchCode;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
   public String getBranchCode() {
        return branchCode;
    }
    public void setBranchCode(String branchCode) {
        this.branchCode = branchCode;
    }
}

用FastJson反序列化(使用版本是1.2.30)

@org.junit.Test
public void testFastJson(){
    String json = "{\"_id\":\"abc\",\"id\":\"1\",\"branch_code\":\"name\"}";
    Model model = JSON.parseObject(json, Model.class);
    Assert.assertEquals((Integer) 1, season.getId());
}

报错:

com.alibaba.fastjson.JSONException: For input string: "abc"
...
Caused by: java.lang.NumberFormatException: For input string: "abc"

如果改成如下,是可以反序列化的

String json = "{\"id\":\"1\",\"_id\":\"abc\",\"branch_code\":\"name\"}";

分析原因是,按顺序反序列化,_id反序列化后是String类型,但实际上idInteger类型,所以就报错了。

请问,我要的是忽略带下划线的属性_idbranch_code,只匹配符合小驼峰的属性,是否可以配置?(在XML文件中配置的方式,我是在SpringMVC框架中前台传数据到后台反序列化时用FastJson)

question

Most helpful comment

JSON.parseObject("...", Model.class, Feature.DisableFieldSmartMatch);

All 2 comments

JSON.parseObject("...", Model.class, Feature.DisableFieldSmartMatch);

非常感谢 @wenshao 及时的回答,问题解决了。
在xml增加如下配置,设置DisableFieldSmartMatch

<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>text/html;charset=UTF-8</value>
            <value>text/plain;charset=UTF-8</value>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
    <property name="fastJsonConfig" ref="fastJsonConfig"/>
</bean>
<bean id="fastJsonConfig" class="com.alibaba.fastjson.support.config.FastJsonConfig">
    <property name="features">
        <list>
            <value>DisableCircularReferenceDetect</value>
            <value>DisableFieldSmartMatch</value>
        </list>
    </property>
    <property name="serializerFeatures">
        <list>
            <!-- Date的日期转换器 默认是yyyy-MM-dd HH:mm:ss 格式-->
            <value>WriteDateUseDateFormat</value>
        </list>
    </property>
</bean>
Was this page helpful?
0 / 5 - 0 ratings