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

序列化对象存缓存后反序列化报错:无法将Object转为String

错误原因分析

你存到缓存里的是完整的JSON对象 {"id":"abcdefg"},但读取时直接调用 mapper.readValue(byteInput, String.class),要求Jackson把整个JSON对象转成String类型。Jackson仅能把纯JSON字符串(比如 "abcdefg")转成String,面对以{开头的JSON对象结构,自然会抛出类型不匹配的异常。

解决方法

有两种可行的修正方案,任选其一即可:

方案一:调整写入逻辑,只缓存id字符串

既然最终要读取的是id的字符串值,没必要将其封装成JSON对象存储,直接序列化id字符串即可:

private void writeInCache (Account account) {
    String bankId = account.getBank().getId();
    ObjectMapper mapper = new ObjectMapper();
    byte[] jsonBytes = mapper.writeValueAsBytes(bankId);
    CacheResponse cacheResponse = cacheClient.create(
        account.getAccountNumber().getBytes(StandardCharsets.UTF_8), 
        jsonBytes
    );
}

读取逻辑无需修改,此时缓存中存储的是"abcdefg",可直接反序列化为String类型。

方案二:调整读取逻辑,先解析JSON对象再提取id

如果必须保留缓存中的JSON对象结构,读取时需先将内容解析为JSON对象,再提取id字段:

public void readFromCache() {
    CacheResponse cacheResponse = cacheClient.get(account.getAccountNumber().getBytes(StandardCharsets.UTF_8));
    if(null != cacheResponse.getValue()){
        ByteArrayInputStream byteInput = new ByteArrayInputStream(cacheResponse.getValue());
        // 先解析成JsonNode对象,再提取id字段
        JsonNode jsonNode = mapper.readValue(byteInput, JsonNode.class);
        bank.setId(jsonNode.get("id").asText());
        // rest code
    }
}

也可以定义一个与缓存结构对应的POJO类,通过反序列化POJO来获取id:

class BankIdDto {
    private String id;
    // 生成getter和setter方法
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
}

读取时的代码改为:

BankIdDto bankIdDto = mapper.readValue(byteInput, BankIdDto.class);
bank.setId(bankIdDto.getId());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:52:40