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

.NET Core中使用System.Text.Json合并两个JSON对象的方法

.NET Core 合并两个JSON并反序列化的实现方案

一、定义匹配目标结构的数据类

根据你期望的合并后JSON结构,创建对应的C#类:

// 存储年份对应字符串数组的字典
public class YearData : Dictionary<string, List<string>> { }

// 存储多个Test项的容器
public class TestContainer : Dictionary<string, YearData> { }

// 最终合并结果的根类
public class MergedJson
{
    public TestContainer Mainjson1 { get; set; }
    public TestContainer Secondjson2 { get; set; }
}

二、解析原始JSON并组装合并对象

1. 处理第一个JSON

第一个JSON的结构直接匹配TestContainer,可直接反序列化:

string firstJson = @"{""Test1"": {""2020"": [""10%"",""10%"",""10%"",""10%""], ""2021"": [""10%"",""30%"",""30%"",""40%""],}, ""Test2"": {""2020"": [""No"",""No"",""No"",""No""], ""2021"": [""No"",""No"",""No"",""No""]}}";

TestContainer mainContainer = JsonSerializer.Deserialize<TestContainer>(firstJson);

2. 处理第二个JSON

第二个JSON中Test3是数组结构,需要先提取数组内的有效数据:

string secondJson = @"{""Test3"": [{""2020"": [""LC"",""Cnd"",""NA"",""LC""], ""2021"": [""LC"",""Cd"",""NA"",""Lty""]}],}";

// 用JsonDocument解析提取Test3的实际数据
using JsonDocument doc = JsonDocument.Parse(secondJson);
JsonElement root = doc.RootElement;
JsonElement test3Array = root.GetProperty("Test3");
YearData test3Data = test3Array[0].Deserialize<YearData>();

// 组装Secondjson2的内容
TestContainer secondContainer = new TestContainer();
secondContainer.Add("Test3", test3Data);
// 按目标示例添加Test4(与Test2内容一致)
secondContainer.Add("Test4", mainContainer["Test2"]);

3. 组装最终合并对象

将两个容器对象赋值到根类中:

MergedJson finalResult = new MergedJson
{
    Mainjson1 = mainContainer,
    Secondjson2 = secondContainer
};

三、生成合并后的JSON(可选)

如果需要输出格式化后的JSON字符串:

string mergedJson = JsonSerializer.Serialize(finalResult, new JsonSerializerOptions { WriteIndented = true });
// 输出结果与你期望的格式一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:47:36