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

C#如何为指定动态键结构的JSON定义对应DTO类并实现序列化构造

解决方案

你的目标JSON结构的两级Key都是动态值(大洲名、国家名都是动态变化的,不是固定属性),所以不需要定义带固定属性的实体类,直接用嵌套泛型字典作为DTO即可,和序列化组件的适配度最高。

1. DTO类型定义

你可以直接使用原生泛型字典类型,无需额外声明自定义类:

// 可直接序列化生成目标JSON的DTO类型:外层key为大洲名,内层key为国家名,值为首都名
Dictionary<string, Dictionary<string, string>> ContinentCountryDto;

如果你需要显式的命名类提高可读性,也可以通过继承Dictionary实现:

// 国家-首都映射类
public class CountryCapitalMap : Dictionary<string, string> {}
// 大洲-国家映射DTO类,直接序列化即可得到目标结构
public class ContinentDto : Dictionary<string, CountryCapitalMap> {}

2. 从已有数据转换为DTO

假设你的Continent类结构如下(按你的描述推导):

public class Continent
{
    // 存储大洲名称,对应值比如"Europe"
    public string Name { get; set; }
    // 当前大洲包含的国家列表
    public List<Country> Countries { get; set; }
}

你可以通过LINQ的ToDictionary方法直接完成转换,转换后的对象可以直接被Newtonsoft.Json、System.Text.Json等序列化组件生成你需要的JSON结构:

// 假设allContinents是你从数据库等数据源查询到的所有大洲数据集合
List<Continent> allContinents = GetContinentsFromDB();

// 转换为可序列化的DTO结构
var dto = allContinents.ToDictionary(
    continent => continent.Name,
    continent => continent.Countries.ToDictionary(
        country => country.Name,
        country => country.Capital
    )
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:45:04