You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将类对象作为参数实现通用Jackson JSON反序列化方法

基础通用实现

Java 可以通过泛型+传入Class<T>类型参数实现需求,改造后的方法如下:

public <T> T fromJson(String config, Class<T> clazz) {
    T result = null;
    try {
        result = mapper.readValue(config, clazz);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return result;
}

调用方式:

// 转换为JobConfig实例
JobConfig jobConfig = utils.fromJson(config, JobConfig.class);
// 新增其他类型直接传入对应Class即可,不需要新增方法
OtherConfig otherConfig = utils.fromJson(otherConfigStr, OtherConfig.class);

支持泛型类型的扩展实现

如果需要反序列化带泛型的类型(比如List<JobConfig>、Map<String, JobConfig>),可以额外重载一个接收JacksonTypeReference的方法:

import com.fasterxml.jackson.core.type.TypeReference;

public <T> T fromJson(String config, TypeReference<T> typeReference) {
    T result = null;
    try {
        result = mapper.readValue(config, typeReference);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return result;
}

调用方式:

List<JobConfig> jobConfigList = utils.fromJson(configListStr, new TypeReference<List<JobConfig>>() {});

补充说明

原实现中捕获异常仅打印堆栈后返回null,可根据业务需要调整异常处理逻辑,比如抛出业务异常、返回Optional<T>空对象等,避免空指针风险。

内容的提问来源于stack exchange,提问作者Shiv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:27:01