alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.74k stars 6.5k forks source link

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

Open ymwangzq opened 2 years ago

ymwangzq commented 2 years ago

复现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);
    }
}
wenshao commented 2 years ago

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