小编Ant*_*Jr.的帖子

如何使用 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)

.net-core asp.net5 .net-5 system.text.json

6
推荐指数
1
解决办法
794
查看次数

标签 统计

.net-5 ×1

.net-core ×1

asp.net5 ×1

system.text.json ×1