c# - 如何在 JSON.NET 中取消转义 unicode
问题描述
我有带有 Unicode 部分的 JSON,例如{ "val1": "\u003c=AA+ \u003e=AA-"}
如何将其转换为没有 Unicode 格式的 JSON?
{"val1": "<=AA+ >=AA-"}
解决方案
Json.NET 取消了 Unicode 序列的转义,因此您可以采用与如何使用 C# 在 .NET 中获取格式化 JSON 的答案JsonTextReader
中使用的方法相同的方法?由Duncan Smart通过直接从 a 流式传输到 a using来重新格式化您的 JSON,而无需进行不必要的转义:JsonTextReader
JsonTextWriter
JsonWriter.WriteToken(JsonReader)
public static partial class JsonExtensions
{
// Adapted from this answer https://stackoverflow.com/a/30329731
// To https://stackoverflow.com/q/2661063
// By Duncan Smart https://stackoverflow.com/users/1278/duncan-smart
public static string JsonPrettify(string json, Formatting formatting = Formatting.Indented)
{
using (var stringReader = new StringReader(json))
using (var stringWriter = new StringWriter())
{
return JsonPrettify(stringReader, stringWriter, formatting).ToString();
}
}
public static TextWriter JsonPrettify(TextReader textReader, TextWriter textWriter, Formatting formatting = Formatting.Indented)
{
// Let caller who allocated the the incoming readers and writers dispose them also
// Disable date recognition since we're just reformatting
using (var jsonReader = new JsonTextReader(textReader) { DateParseHandling = DateParseHandling.None, CloseInput = false })
using (var jsonWriter = new JsonTextWriter(textWriter) { Formatting = formatting, CloseOutput = false })
{
jsonWriter.WriteToken(jsonReader);
}
return textWriter;
}
}
使用这种方法,下面的代码:
var json = @"{ ""val1"": ""\u003c=AA+ \u003e=AA-""}";
var unescapedJson = JsonExtensions.JsonPrettify(json, Formatting.None);
Console.WriteLine("Unescaped JSON: {0}", unescapedJson);
输出
Unescaped JSON: {"val1":"<=AA+ >=AA-"}
演示小提琴在这里。
推荐阅读
- azure - 从 Azure 构建/发布管道访问 Azure Key Vault
- android - 如何在应用发明者平台中添加喷射器
- python - 在不损失精度的情况下将双精度从 C++ 转移到 python
- java - 出现错误原因:java.lang.ClassNotFoundException:org.springframework.core.ReactiveAdapterRegistry
- cgal - 使用 CGAL 时出错:“Alpha_shape_cell_base_3”类没有名为“hide_points”的成员
- javascript - Modernizr:如果不支持,则在后台删除带有 .webp 的元素
- c# - 添加格式为 00:00 的计时器?
- shell - 排序不适用于带有文本文件的 -h
- kotlin - 我需要哪个 Kotlin 下载?
- python-3.x - 返回 ValueError 的日期单元格的位置:('Unknown string format:', '2020-4-')