我有JSON和Unicode部分,例如{ "val1": "\u003c=AA+ \u003e=AA-"}
如何将其转换为没有Unicode格式的JSON?
{"val1": "<=AA+ >=AA-"}
答案 0 :(得分:0)
Json.NET在JsonTextReader
内转义Unicode序列,因此您可以采用与this answer到{em> How do I get formatted JSON in .NET using C#? 的Duncan Smart所使用的相同方法。 },使用JsonWriter.WriteToken(JsonReader)
从JsonTextReader
直接流到JsonTextWriter
,重新格式化JSON,而无需不必要的转义:
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-"}
演示小提琴here。
答案 1 :(得分:-1)
我在Linqpad中尝试了以下方法,它确实有效。
var s = @"{ ""val1"": ""\u003c=AA+ \u003e=AA-""}";
System.Text.RegularExpressions.Regex.Unescape(s).Dump();