问题描述
使用 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 });
}