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

问题描述

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

thread '<unnamed>' panicked at 'there is no timer running,must be called from the context of Tokio runtime',/home/admin/.cargo/registry/src/github.com-1ecc6299db9ec823/tokio-1.0.1/src/time/driver/handle.rs:50:18

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

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

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

解决方法

这有效:

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...