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

如何使用Gson一步反序列化含Base64编码data字段的JSON数据

使用Gson一步反序列化含Base64编码data字段的JSON

别担心,咱们用Gson自定义反序列化逻辑就能一步搞定这个需求,我给你一步步拆解清楚:

步骤1:定义对应的实体类

先把内层的用户类和外层的响应类定义好,注意外层响应的data直接定义成我们要的List<User>类型,不用先存成字符串:

// 用户实体类
public class User {
    private int id;
    private String name;

    // 记得生成无参构造、getter和setter,或者用Lombok简化代码
    public User() {}

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

// 外层接口响应类
public class ApiResponse {
    private int code;
    private String message;
    private List<User> data;

    // 同样需要无参构造、getter和setter
    public ApiResponse() {}

    public int getCode() { return code; }
    public void setCode(int code) { this.code = code; }
    public String getMessage() { return message; }
    public void setMessage(String message) { this.message = message; }
    public List<User> getData() { return data; }
    public void setData(List<User> data) { this.data = data; }
}

步骤2:自定义JsonDeserializer处理Base64解码

核心就是写一个自定义的反序列化器,告诉Gson怎么处理data字段的Base64编码:

import com.google.gson.*;
import java.lang.reflect.Type;
import java.util.Base64;
import java.util.List;

public class ApiResponseDeserializer implements JsonDeserializer<ApiResponse> {
    private final Gson gson = new Gson();

    @Override
    public ApiResponse deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = jsonElement.getAsJsonObject();
        
        // 先解析外层不需要特殊处理的字段
        ApiResponse response = new ApiResponse();
        response.setCode(jsonObject.get("code").getAsInt());
        response.setMessage(jsonObject.get("message").getAsString());
        
        // 处理Base64编码的data字段:解码转成原始JSON,再转成List<User>
        String base64Data = jsonObject.get("data").getAsString();
        byte[] decodedBytes = Base64.getDecoder().decode(base64Data);
        String dataJson = new String(decodedBytes);
        
        List<User> userList = gson.fromJson(dataJson, new TypeToken<List<User>>(){}.getType());
        response.setData(userList);
        
        return response;
    }
}

步骤3:注册解析器并一步完成反序列化

把自定义解析器注册到GsonBuilder里,创建Gson实例后直接调用一次fromJson就能完成整个反序列化流程:

public class Main {
    public static void main(String[] args) {
        // 你的原始JSON字符串
        String json = "{\"code\":1, \"message\":\"ok\", \"data\":\"W3tpZDoxLCBuYW1lOiJUb20ifSx7aWQ6MiwgbmFtZToiSmFjayJ9LHtpZDozLCBuYW1lOiJMdWNpYSJ9XQ==\"}";
        
        // 注册自定义解析器,创建Gson实例
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(ApiResponse.class, new ApiResponseDeserializer())
                .create();
        
        // 一步反序列化完成
        ApiResponse response = gson.fromJson(json, ApiResponse.class);
        
        // 测试输出验证结果
        System.out.println("返回码: " + response.getCode());
        System.out.println("提示信息: " + response.getMessage());
        response.getData().forEach(user -> System.out.println("用户ID: " + user.getId() + ",用户名: " + user.getName()));
    }
}

原理说明

Gson的JsonDeserializer允许我们接管指定类的反序列化逻辑,这里我们先处理外层普通字段,再手动解码data的Base64内容,把解码后的JSON转成目标List<User>,最后组装成完整的ApiResponse对象,全程只需要一次fromJson调用,完美实现一步反序列化的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:06:42