如何使用 System.Text.Json 对未知对象进行漂亮的打印

LP1*_*P13 6 .net-core asp.net5 .net-5 system.text.json

使用 System.Text.Json 我可以使用序列化选项漂亮地打印 json。

var options = new JsonSerializerOptions{ WriteIndented = true };
jsonString = JsonSerializer.Serialize(typeToSerialize, options);
Run Code Online (Sandbox Code Playgroud)

但是,我有字符串 JSON 并且不知道 concreate 类型。我如何漂亮地打印 JSON 字符串?

我的旧代码使用 Newtonsoft,无需序列化/反序列化即可完成

public static string JsonPrettify(this string json)
{
    if (string.IsNullOrEmpty(json))
    {
        return json;
    }

    using (var stringReader = new StringReader(json))
    using (var stringWriter = new StringWriter())
    {
        var jsonReader = new JsonTextReader(stringReader);
        var jsonWriter = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
        jsonWriter.WriteToken(jsonReader);
        return stringWriter.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

dlu*_*mpp 66

这有效:

using System.Text.Json;
public static string JsonPrettify(this string json)
{
    using var jDoc = JsonDocument.Parse(json);
    return JsonSerializer.Serialize(jDoc, new JsonSerializerOptions { WriteIndented = true });
}
Run Code Online (Sandbox Code Playgroud)

  • “JsonDocument”是“IDisposable”,必须将其释放才能将池化内存返回到内存池以供重用。 (5认同)
  • 你是对的,@dbc。我添加了一个使用。接得好。 (2认同)