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

.NET Core 5中使用System.Text.Json替代JObject构建JSON对象

.NET Core 5 下 System.Text.Json 实现等效动态JSON构建

.NET Core 5 搭载的 System.Text.Json 版本未提供 .NET 6+ 才加入的 JsonObject/JsonNode 动态JSON操作API,可通过以下两种方式实现与原有Newtonsoft.Json代码完全一致的输出效果:


方案1:使用嵌套字典实现(最接近原有JObject的编码体验)

System.Text.Json 原生支持将 Dictionary<string, object> 序列化为标准JSON对象,嵌套字典对应嵌套JSON对象,编码逻辑和原有JObject/JProperty的写法高度相似,迁移成本最低。

  • 字典的string类型键会直接序列化为JSON属性名,和JProperty的行为完全一致
  • 值类型传入字符串、数字、布尔值、嵌套字典时,都会被正确序列化为对应的JSON值类型
  • 序列化规则(日期格式、枚举转换、字符转义等)统一在JsonSerializerOptions中配置,和普通类型序列化逻辑通用

实现代码如下:

using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

// 初始化顶层JSON对象,对应原有new JObject()
var jsonDict = new Dictionary<string, object>
{
    // 对应原有JProperty("Status", ...)
    ["Status"] = result.Status.ToString(),
    // 对应原有JProperty("Duration", ...)
    ["Duration"] = result.TotalDuration.TotalSeconds.ToString()
};

// 对应原有Entries判空逻辑
if (result.Entries.Any())
{
    var entriesDict = new Dictionary<string, object>();
    foreach (var entry in result.Entries)
    {
        // 对应每个entry的嵌套JObject
        entriesDict[entry.Key] = new Dictionary<string, object>
        {
            ["Status"] = entry.Value.Status.ToString(),
            ["Duration"] = entry.Value.Duration.TotalSeconds.ToString(),
            ["Description"] = entry.Value.Description
        };
    }
    // 对应原有json.Add(new JProperty("result", entries))
    jsonDict["result"] = entriesDict;
}

// 最终序列化为JSON字符串
var finalJson = JsonSerializer.Serialize(jsonDict, new JsonSerializerOptions
{
    PropertyNamingPolicy = null, // 保持属性名大小写和传入一致,匹配Newtonsoft默认行为
    WriteIndented = false // 按需开启格式化缩进
});

方案2:使用Utf8JsonWriter直接写入(性能最优)

如果对序列化性能有更高要求,可以直接使用Utf8JsonWriter按顺序写入JSON结构,避免中间字典对象的内存分配,输出结构和原有逻辑完全对齐:

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

using var stream = new MemoryStream();
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions
{
    Indented = false // 按需配置格式化缩进
});

writer.WriteStartObject();
// 写入顶层Status、Duration字段
writer.WriteString("Status", result.Status.ToString());
writer.WriteString("Duration", result.TotalDuration.TotalSeconds.ToString());

if (result.Entries.Any())
{
    writer.WritePropertyName("result");
    writer.WriteStartObject();
    foreach (var entry in result.Entries)
    {
        writer.WritePropertyName(entry.Key);
        writer.WriteStartObject();
        writer.WriteString("Status", entry.Value.Status.ToString());
        writer.WriteString("Duration", entry.Value.Duration.TotalSeconds.ToString());
        writer.WriteString("Description", entry.Value.Description);
        writer.WriteEndObject();
    }
    writer.WriteEndObject();
}

writer.WriteEndObject();
writer.Flush();

var finalJson = Encoding.UTF8.GetString(stream.ToArray());

两种方案输出的JSON结构和原有Newtonsoft.Json实现完全一致,无需升级框架版本即可使用。如果后续项目升级到.NET 6及以上版本,可直接替换为内置的JsonNode/JsonObjectAPI获得更友好的动态操作体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:48:21