fastjson 从 1.2.69 升级到 1.2.83,@JSONField 行为存在差异

brgchamk  于 2022-10-27  发布在  其他
关注(0)|答案(1)|浏览(764)

复现case如下:用 1.2.69 和 1.2.83 版本的 fastjson 会得出不同的结果

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

import lombok.Data;

/**

* @author wangzhiqian
* Created on 2022/8/19
* /

class FastJsonTest {

    @Data
    public static class SomeModel {
        private String id;
        @JSONField(name = "some_value")
        private int someValue;
    }

    /**

* fastjson 1.2.69 即使标注了 JSONField, 仍然会用 propertyName 解析注入
* 但是 fastjson 1.2.83 只会根据 JSONField  声明的 field 注入
* /

    @Test
    void testFastJson1() {
        String json1 = "{\"id\":\"135951990146386429\",\"someValue\":1}";
        SomeModel dto1 = JSON.parseObject(json1, SomeModel.class);
        Assertions.assertEquals(0, dto1.someValue);
    }

    @Test
    void testFastJson2() {
        String json1 = "{\"id\":\"135951990146386429\",\"some_value\":1}";
        SomeModel dto1 = JSON.parseObject(json1, SomeModel.class);
        Assertions.assertEquals(1, dto1.someValue);
    }
}
j13ufse2

j13ufse21#

https://github.com/alibaba/fastjson2/releases
升级到2.0.x版本,使用非兼容API可以解决你的问题,如下:

import com.alibaba.fastjson2.annotation.JSONField;
import com.alibaba.fastjson2.JSON;
import lombok.Data;
import org.junit.jupiter.api.Test;

import static org.junit.Assert.assertEquals;

public class Issue4266 {
    @Data
    public static class SomeModel {
        private String id;
        @JSONField(name = "some_value")
        private int someValue;
    }

    @Test
    public void test1() {
        String json1 = "{\"id\":\"135951990146386429\",\"some_value\":1}";
        SomeModel dto1 = JSON.parseObject(json1, SomeModel.class);
        assertEquals(1, dto1.someValue);
    }

    @Test
    public void test2() {
        String json1 = "{\"id\":\"135951990146386429\",\"someValue\":1}";
        SomeModel dto1 = JSON.parseObject(json1, SomeModel.class);
        assertEquals(0, dto1.someValue);
    }
}

相关问题