Avoid accented characters on utf-8 json

the code below produces this output:

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

I need to change this, I suppose I need to change something in the encoding, but I do not know what:

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

the 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();
}
+4
source share
1 answer

Like other users, 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());
    }
}

exits

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

https://dotnetfiddle.net/s5VppR

+7
source

Source: https://habr.com/ru/post/1584926/


All Articles