LP1*_*P13 6 .net-core asp.net5 .net-5 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)
dlu*_*mpp 66
这有效:
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 });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
794 次 |
| 最近记录: |