escape accented chars on utf-8 json

北城以北 提交于 2019-12-12 11:53:11

问题


the code below produce this output:

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

i need to change to this, i suppose i've to change something on encoding but i don't know what:

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

code:

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();
}

回答1:


Like others said, you want to use 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());
    }
}

outputs

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

https://dotnetfiddle.net/s5VppR



来源:https://stackoverflow.com/questions/29899386/escape-accented-chars-on-utf-8-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!