开发者社区> 问答> 正文

fastjson 2 是否考虑支持接口的反序列化?

希望可以支持接口的反序列化。

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

展开
收起
飘飘斯嘉丽 2023-04-21 11:21:44 170 0
1 条回答
写回答
取消 提交回答
  • 找到序列化失败的原因了,是2.0.11的bug,回退到2.0.10就没有问题了。

    相关issue:#649

    使用2.0.10的测试结果如下:

    org.opentest4j.AssertionFailedError: expected: but was: Expected :jhahah Actual :null

    原回答者GitHub用户DoneSpeak

    2023-04-21 14:18:19
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载