Fastjson json字符串怎样直接反序列化为对象

该文章为原创(转载请注明出处):Fastjson json字符串怎样直接反序列化为对象? - 简书 (jianshu.com)

真实业务场景

因为某种原因(可能是前端定义、可能是远程调用外部已经定义),json接收过来是json字符串 希望在接受的时候直接能够反序列化为对象

java 复制代码
@Data
public static class TestOuter {
    private Stirng bizJson;
}
@Data
public static class BizJson {
    private String name;
}
json 复制代码
{
    "bizJson": "{\"name\":\"testName\"}"
}

上述案例,返回 我想要得到 BizJsonDTO对象只能手动处理

java 复制代码
public class Test {
    public static void main(String[] args) {
        TestOuter testOuter = JSON.parse("", TestOuter.class);
        String bizJsonString = testOuter.getBizJson();
        BizJson bizJson = JSON.parse(bizJsonString, BizJson.class);
        //...
    }
}

需要达成的目的

我希望第一次反序列化的时候就能够 得到BizJsonDTO,同时还能兼容 json 的场景

方案思路

实现一个 字符串的反序列化器

代码实现

java 复制代码
@Data
public static class TestOuter {
    @JSONField(deserializeUsing = JsonStringDeserializer.class)
    private BizJson bizJson;
}
@Data
public static class BizJson {
    private String name;
}
public static void main(String[] args) {
    // 字符串场景 bizJson = "{\"name\": \"123\"}"
    JSON.parseObject("{\"bizJson\": \"{\\\"name\\\": \\\"123\\\"}\"}", TestOuter.class);
    // 对象场景 bizJson = {"name": "123"}
    JSON.parseObject("{\"bizJson\": {\"name\": \"123\"}}", TestOuter.class);
}
java 复制代码
import java.lang.reflect.Type;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;

/**
 * 适用于:对应字段的值 非json对象 而是 json的字符串
 *
 * @author fuhangbo.hanger.uhfun
 **/
public class JsonStringDeserializer implements ObjectDeserializer {

    @Override
    public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        // json字符串场景
        if (parser.lexer.token() == LITERAL_STRING) {
            String jsonString = (String)parser.parse(fieldName);
            return JSON.parseObject(jsonString, type);
        }
        // json对象场景
        if (parser.lexer.token() == LBRACE) {
            return parser.parseObject(type, fieldName);
        }
        throw new UnsupportedOperationException();
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }
}

该文章为原创(转载请注明出处):Fastjson json字符串怎样直接反序列化为对象? - 简书 (jianshu.com)

相关推荐
爱吃烤鸡翅的酸菜鱼13 小时前
Spring Boot 实现 WebSocket 实时通信:从原理到生产级实战
java·开发语言·spring boot·后端·websocket·spring
uzong20 小时前
Mermaid: AI 时代画图的魔法工具
后端·架构
q***697720 小时前
Spring Boot与MyBatis
spring boot·后端·mybatis
IUGEI1 天前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
间彧1 天前
GraalVM Native Image:跨平台能力与编译模式深度解析
后端
间彧1 天前
GraalVM Native Image 与传统 JVM 内存管理:云原生时代的技术选型指南
后端
r***12381 天前
SpringBoot最佳实践之 - 使用AOP记录操作日志
java·spring boot·后端
b***74881 天前
前端GraphQL案例
前端·后端·graphql
LSL666_1 天前
SpringBoot自动配置类
java·spring boot·后端·自动配置类
q***78371 天前
Spring Boot 3.X:Unable to connect to Redis错误记录
spring boot·redis·后端