本文介绍了如何使用Json.NET StringEscapeHandling.EscapeNonAscii的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最新版本的Json.NET(4.5.11)包含 StringEscapeHandling.EscapeNonAscii ,它转义所有非ASCII字符。但是,我不知道如何使用它。该文档似乎没有任何可以找到的例子(只有一个发布说明)。

The latest release of Json.NET (4.5.11) contains StringEscapeHandling.EscapeNonAscii, which escapes all non ASCII chars. But, I can't figure out how to use it. The docs don't seem to have any examples that I can find (only a release note announcing it).

有人可以显示将对象序列化为JSON的示例字符串,使用 EscapeNonAscii

Could someone show an example of serializing an object into a JSON string, using EscapeNonAscii?

推荐答案

也许这个例子可以帮助

string obj = "abcn\n\rüö&/<>";
Console.WriteLine(Serialize(obj, StringEscapeHandling.Default));
Console.WriteLine(Serialize(obj, StringEscapeHandling.EscapeHtml));
Console.WriteLine(Serialize(obj, StringEscapeHandling.EscapeNonAscii));







public static string Serialize(object o,StringEscapeHandling stringEscapeHandling)
{
    StringWriter wr = new StringWriter();
    var jsonWriter = new JsonTextWriter(wr);
    jsonWriter.StringEscapeHandling = stringEscapeHandling;
    new JsonSerializer().Serialize(jsonWriter,o);
    return wr.ToString();
}

这篇关于如何使用Json.NET StringEscapeHandling.EscapeNonAscii的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:28