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

.NET Core API中用System.Text.Json在JSON顶部添加新节点

实现方案

使用System.Text.Json(原生库)

如果项目只依赖.NET Core自带的System.Text.Json,可以通过JsonDocument和Utf8JsonWriter动态修改JSON结构,无需定义实体类:

using System.IO;
using System.Text.Json;

public static string WrapNodesIntoNewNode(string originalJson)
{
    // 解析原始JSON
    using JsonDocument doc = JsonDocument.Parse(originalJson);
    JsonElement rootElement = doc.RootElement;

    // 构造新的JSON结构
    using var memoryStream = new MemoryStream();
    using var writer = new Utf8JsonWriter(memoryStream, new JsonWriterOptions { Indented = true });

    writer.WriteStartObject();
    writer.WritePropertyName("Newnode");
    // 将原始根节点的所有内容写入到Newnode属性下
    rootElement.WriteTo(writer);
    writer.WriteEndObject();

    writer.Flush();
    memoryStream.Position = 0;

    // 将MemoryStream转换为字符串返回
    using var streamReader = new StreamReader(memoryStream);
    return streamReader.ReadToEnd();
}

调用示例:

string originalJson = @"{""Test1"": {""2020"": [""40%"",""40%"",""40%"",""40%""], ""2021"": [""50%"",""30%"",""30%"",""40%""]}, ""Test2"": {""2020"": [""No"",""No"",""No"",""No""], ""2021"": [""No"",""No"",""No"",""No""]}}";
string targetJson = WrapNodesIntoNewNode(originalJson);
Console.WriteLine(targetJson);

使用Newtonsoft.Json的JObject

如果项目中已经引入了Newtonsoft.Json(Json.NET),可以用更简洁的方式实现:

using Newtonsoft.Json.Linq;

public static string WrapNodesIntoNewNode(string originalJson)
{
    JObject originalObj = JObject.Parse(originalJson);
    JObject newRootObj = new JObject
    {
        ["Newnode"] = originalObj
    };
    // 格式化输出带缩进的JSON
    return newRootObj.ToString(Newtonsoft.Json.Formatting.Indented);
}

说明

  • 两种方案都支持动态修改JSON结构,无需提前定义对应的数据模型类
  • 原生方案更轻量化,适合未引入第三方JSON库的场景;Newtonsoft.Json方案代码更简洁,适合已使用该库的项目

内容的提问来源于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 22:57:23