c# - 在 utf-8 json 上转义重音字符

标签 c# json character-encoding json.net

下面的代码产生这个输出:

{"x": "Art. 120 - Incapacità di intendere o di volere"}

我需要对此进行更改,我想我必须更改一些编码但我不知道是什么:

{"x": "Art. 120 - Incapacit\u00e0 di intendere o di volere"}

代码:

string label = "Art. 120 - Incapacità di intendere o di volere";
JObject j = new JObject();
j.Add(new JProperty("x", label));
string s = j.ToString();
Encoding encoding = new UTF8Encoding(false);
string filename = @"c:\temp\test.json";
using (FileStream oFileStream = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
    {
    using (StreamWriter oStreamWriter = new StreamWriter(oFileStream, encoding))
    {
        oStreamWriter.Write(j.ToString());
        oStreamWriter.Flush();
        oStreamWriter.Close();
    }
    oFileStream.Close();
}

最佳答案

正如其他人所说,您想使用 StringEscapeHandling.EscapeNonAscii

using System;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class Program
{
    public static void Main()
    {
        string label = "Art. 120 - Incapacità di intendere o di volere";
        JObject j = new JObject();
        j.Add(new JProperty("x", label));
        string s = j.ToString();

        var sr = new StringWriter();
        var jsonWriter = new JsonTextWriter(sr) {
            StringEscapeHandling =  StringEscapeHandling.EscapeNonAscii
        };
        new JsonSerializer().Serialize(jsonWriter, j);

        Console.Out.WriteLine(sr.ToString());
    }
}

输出

{"x":"Art. 120 - Incapacit\u00e0 di intendere o di volere"}

https://dotnetfiddle.net/s5VppR

关于c# - 在 utf-8 json 上转义重音字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29899386/

相关文章:

javascript - 如何使用异步数据更新 Angular Directive(指令)

json - AoT + Webpack + json动态require

php - 告诉另一个域上的 Controller 有新数据

PHP:如何对 U+FFFD 进行编码以进行替换?

c# - 我如何做等效的 TaskCompletionSource<nothing>?

c# - 共享程序集 - 是否需要签名?

c# - 为什么我在执行 HTTP POST 时用完了流的字节数?

c# - 告诉 FxCop 另一个方法正在调用 dispose

在我的 char 指针末尾添加了 C++ 奇怪的编码字符

Perl UTF8 编码错误。 LWP::UserAgent->decoded_content 或 Encode::decode 都不起作用。其他想法?