.net-core - 如何将 System.Text.JsonElement 打印(格式化)到字符串
问题描述
将现有JsonElement
的格式化为格式化的 JSON 字符串的 API 在哪里。ToString()
API 不提供任何格式选项。
回退到使用 Newtonsoft 很烦人
Newtonsoft.Json.Linq.JValue
.Parse(myJsonElement.GetRawText())
.ToString(Newtonsoft.Json.Formatting.Indented)
解决方案
您可以重新序列化您的JsonElement
withJsonSerializer
和 set JsonSerializerOptions.WriteIndented = true
,例如在扩展方法中:
public static partial class JsonExtensions
{
public static string ToString(this JsonElement element, bool indent)
=> element.ValueKind == JsonValueKind.Undefined ? "" : JsonSerializer.Serialize(element, new JsonSerializerOptions { WriteIndented = indent } );
}
然后做:
var indentedJson = myJsonElement.ToString(true)
笔记:
检查是为了避免默认(未初始化)结构
JsonValueKind.Undefined
的异常;不会抛出默认值,因此格式化版本也不应该。JsonElement
JsonElement.ToString()
JsonElement
如其他答案所示,使用
Utf8JsonWriter
while 设置编写也可以。JsonWriterOptions.Indented
演示小提琴在这里。
推荐阅读
- maven - Maven 项目初始化程序
- testing - 我是 Protractor 测试的新手,请您告诉我如何为登录网页编写脚本并转到下一页
- google-chrome - 在 Windows 和 Android 上使用 Chrome 选择证书
- python - 如何根据其他非相关模型过滤django模型
- java - Spring - 使用 x-www-form-urlencoded 错误编码 POST 请求
- c# - EF 两个干扰上下文
- ionic-framework - Ionic 4 build for release 不工作,调试 apk 工作
- json - 如何在sql查询中调用Json
- c - printf() 重定向到命令行中的文件 (Cygwin)
- django - 对于轮询其他 API 的 API,我应该使用任务队列 (Celery)、ayncio 还是都不使用?