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

如何使用Java Gson根据type字段解析动态JSON对象

Gson根据type字段动态解析不同类实例的实现方案

定义的Java类

class X {
  public String name;
  public int age;
}
class Y {
  public float score;
}

待解析的JSON格式

存在两种结构:

类型为X的JSON

{
  "type": "X",
  "data": {
    "name": "myname",
    "age": 20
  }
}

类型为Y的JSON

{
  "type": "Y",
  "data": {
    "score": 10
  }
}

问题

如何使用Gson解析上述JSON,使得当type字段为X时,将data解析为X类实例;当type为Y时,解析为Y类实例?


解决方案

方法一:分步解析(简单直观)

先解析JSON外层结构获取type,再根据类型针对性解析data字段:

  1. 定义临时类承载外层结构
class TempWrapper {
    public String type;
    public JsonElement data; // 保留原始JSON节点,后续再解析
}
  1. 核心解析逻辑
Gson gson = new Gson();
String jsonStr = "你的JSON字符串";

// 先解析外层拿到类型和原始data
TempWrapper wrapper = gson.fromJson(jsonStr, TempWrapper.class);

Object result;
switch (wrapper.type) {
    case "X":
        result = gson.fromJson(wrapper.data, X.class);
        break;
    case "Y":
        result = gson.fromJson(wrapper.data, Y.class);
        break;
    default:
        throw new IllegalArgumentException("未知类型: " + wrapper.type);
}

// 后续使用实例
if (result instanceof X) {
    X xObj = (X) result;
    System.out.println(xObj.name + ", " + xObj.age);
} else if (result instanceof Y) {
    Y yObj = (Y) result;
    System.out.println(yObj.score);
}

方法二:自定义TypeAdapter(优雅适配复杂场景)

通过自定义TypeAdapter自动完成类型判断与解析:

  1. 可选:定义统一接口(方便后续扩展)
interface BaseType {}

// 修改X、Y实现接口
class X implements BaseType {
    public String name;
    public int age;
}

class Y implements BaseType {
    public float score;
}
  1. 自定义TypeAdapter
class DynamicTypeAdapter extends TypeAdapter<BaseType> {
    private final Gson gson = new Gson();

    @Override
    public void write(JsonWriter out, BaseType value) throws IOException {
        // 序列化逻辑按需实现,本文重点为解析
        gson.getAdapter(value.getClass()).write(out, value);
    }

    @Override
    public BaseType read(JsonReader in) throws IOException {
        JsonObject jsonObject = gson.fromJson(in, JsonObject.class);
        String type = jsonObject.get("type").getAsString();
        JsonElement data = jsonObject.get("data");

        switch (type) {
            case "X":
                return gson.fromJson(data, X.class);
            case "Y":
                return gson.fromJson(data, Y.class);
            default:
                throw new IOException("未知类型: " + type);
        }
    }
}
  1. 使用自定义适配器解析
Gson gson = new GsonBuilder()
        .registerTypeAdapter(BaseType.class, new DynamicTypeAdapter())
        .create();

String jsonStr = "你的JSON字符串";
BaseType result = gson.fromJson(jsonStr, BaseType.class);

// 处理解析结果
if (result instanceof X) {
    X xObj = (X) result;
    // 操作X实例
} else if (result instanceof Y) {
    Y yObj = (Y) result;
    // 操作Y实例
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:10:14