希望可以支持接口的反序列化。
Fastjson1 实现
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.alibaba.fastjson.JSON; import com.fasterxml.jackson.core.JsonProcessingException; import org.junit.Test;
public class TestFastjsonDeserializeInterface {
static interface Entity {
    String getName();
}
// 不支持动态代理
@Test
public void testInterfaceProxy() throws JsonProcessingException {
    final var EXPECTED_NAME = "jhahah";
    String jsonString = JSON.toJSONString(new Entity() {
        @Override
        public String getName() {
            return EXPECTED_NAME;
        }
    });
    Entity result = JSON.parseObject(jsonString, Entity.class);
    // actual: null
    assertEquals(EXPECTED_NAME, result.getName());
}
}
Fastjson2 实现
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>2.0.10</version>
    </dependency>
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.alibaba.fastjson2.JSON; import org.junit.Test;
public class TestFastjsonDeserializeInterface {
static interface Entity {
    String getName();
}
// 不支持动态代理
@Test
public void testInterfaceProxy() {
    final var EXPECTED_NAME = "jhahah";
    String jsonString = JSON.toJSONString(new Entity() {
        @Override
        public String getName() {
            return EXPECTED_NAME;
        }
    });
    Entity result = JSON.parseObject(jsonString, Entity.class);
    // actual: null
    assertEquals(EXPECTED_NAME, result.getName());
}
// 不支持动态代理
@Test
public void testDeserialize() {
    final var EXPECTED_NAME = "jhahah";
    var jsonString = String.format("{\"name\":\"%s\"}", EXPECTED_NAME);
    Entity result = JSON.parseObject(jsonString, Entity.class);
    // actual: null
    assertEquals(EXPECTED_NAME, result.getName());
}
}
测试结果:
org.opentest4j.AssertionFailedError: expected: but was: Expected :jhahah Actual :null
原提问者GitHub用户DoneSpeak
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
找到序列化失败的原因了,是2.0.11的bug,回退到2.0.10就没有问题了。
相关issue:#649
使用2.0.10的测试结果如下:
org.opentest4j.AssertionFailedError: expected: but was: Expected :jhahah Actual :null
原回答者GitHub用户DoneSpeak