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

如何使用Gson序列化时将子类名作为JSON的键输出

实现方案

完全可以实现,两种常用实现方式如下:

方案1:自定义序列化适配器(适配Team类保留原有字段逻辑)

如果你的Team类还有其他字段需要一起序列化,推荐用自定义Gson序列化器实现:

第一步:编写Team类的自定义序列化器

import com.google.gson.*;
import java.lang.reflect.Type;

public class TeamSerializer implements JsonSerializer<Team> {
    @Override
    public JsonElement serialize(Team team, Type type, JsonSerializationContext context) {
        JsonObject result = new JsonObject();
        Country country = team.getCountry();
        // 取实现类的简单类名作为JSON的key
        String keyName = country.getClass().getSimpleName();
        result.add(keyName, context.serialize(country));
        // 如果Team有其他字段需要序列化,在这里手动添加即可,例如:
        // result.addProperty("teamName", team.getTeamName());
        return result;
    }
}

第二步:修改main方法的Gson初始化逻辑

public static void main(String[] args) {
    India c = new India();
    c.language = "Hindi";
    Team a = new Team();
    a.setCountry(c);
    // 注册自定义序列化器
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Team.class, new TeamSerializer())
            .create();
    System.out.println(gson.toJson(a));
}

执行后即可输出目标格式{"India":{"language":"Hindi"}}。

方案2:组装Map结构直接序列化(无额外字段时最简方案)

如果不需要保留Team类的其他字段,直接把数据组装为Map再序列化即可,不需要自定义适配器:

public static void main(String[] args) {
    India c = new India();
    c.language = "Hindi";
    // 手动构建key为类名、value为国家对象的Map
    Map<String, Country> outputMap = new HashMap<>();
    outputMap.put(c.getClass().getSimpleName(), c);
    System.out.println(new Gson().toJson(outputMap));
}

扩展说明

如果需要自定义key名称(不想直接使用类名),可以给Country接口添加自定义方法获取别名,示例如下:

public interface Country {
    // 每个实现类返回自定义的JSON key值
    String getJsonKey();
}

// India类实现对应方法
public class India implements Country {
    public String language;
    @Override
    public String getJsonKey() {
        // 这里可以返回任意你需要的key值,比如"india"、"印度"等
        return "India";
    }
}

后续序列化时取country.getJsonKey()作为key即可,灵活性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:06:01