如何将 System.Text.JsonElement 漂亮地打印(格式化)到字符串

Aar*_*don 5 .net-core system.text.json

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

重新使用 Newtonsoft 很烦人

Newtonsoft.Json.Linq.JValue
  .Parse(myJsonElement.GetRawText())
  .ToString(Newtonsoft.Json.Formatting.Indented)
Run Code Online (Sandbox Code Playgroud)

dbc*_*dbc 10

您可以重新序列化您的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 } );
}
Run Code Online (Sandbox Code Playgroud)

然后执行以下操作:

var indentedJson = myJsonElement.ToString(true)
Run Code Online (Sandbox Code Playgroud)

笔记:

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

  • 使用其他答案中所示的Utf8JsonWriterwhile 设置进行编写JsonWriterOptions.Indented也可以。

演示小提琴在这里