【问题标题】:How to pretty print using System.Text.Json for unknown object如何使用 System.Text.Json 漂亮地打印未知对象
【发布时间】:2021-04-13 16:00:26
【问题描述】:

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

var options = new JsonSerializerOptions{ WriteIndented = true };
jsonString = JsonSerializer.Serialize(typeToSerialize, options);

但是,我有字符串 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();
    }
}

【问题讨论】:

标签: .net-core .net-5 system.text.json asp.net5


【解决方案1】:

这行得通:

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 });
}

【讨论】:

  • JsonDocumentIDisposable,并且必须被释放才能将池化内存返回到内存池以供重用。
  • 你是对的,@dbc。我添加了一个使用。很好的收获。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 2011-08-05
  • 2010-12-26
相关资源
最近更新 更多