Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape accented chars on utf-8 json

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();
}
like image 963
FDB Avatar asked Apr 27 '15 15:04

FDB


1 Answers

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

like image 130
gaiazov Avatar answered Oct 20 '22 01:10

gaiazov