首页 > 解决方案 > 如何将 System.Text.JsonElement 打印(格式化)到字符串

问题描述

将现有JsonElement的格式化为格式化的 JSON 字符串的 API 在哪里。ToString()API 不提供任何格式选项。

回退到使用 Newtonsoft 很烦人

Newtonsoft.Json.Linq.JValue
  .Parse(myJsonElement.GetRawText())
  .ToString(Newtonsoft.Json.Formatting.Indented)

标签: .net-coresystem.text.json

解决方案


您可以重新序列化您的JsonElementwithJsonSerializer和 set JsonSerializerOptions.WriteIndented = true,例如在扩展方法中:

public static partial class JsonExtensions
{
    public static string ToString(this JsonElement element, bool indent)
        => element.ValueKind == JsonValueKind.Undefined ? "" : JsonSerializer.Serialize(element, new JsonSerializerOptions { WriteIndented = indent } );
}

然后做:

var indentedJson = myJsonElement.ToString(true)

笔记:

  • 检查是为了避免默认(未初始化)结构JsonValueKind.Undefined的异常;不会抛出默认值,因此格式化版本也不应该。JsonElementJsonElement.ToString()JsonElement

  • 如其他答案所示,使用Utf8JsonWriterwhile 设置编写也可以。JsonWriterOptions.Indented

演示小提琴在这里


推荐阅读