Serialization of foreign languages ​​using JSON.Net

I want to serialize a .NET object in JSON that contains strings in a foreign language, such as Chinese or Russian. When I do this (using the code below) in the resulting JSON, it encodes those characters that are stored as strings like "?" instead of the desired unicode char.

using Newtonsoft.Json;

var serialized = JsonConvert.SerializeObject(myObj, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All, Formatting = Newtonsoft.Json.Formatting.Indented });

Is there a way to use the JSON.Net serializer with foreign languages?

eg

אספירין (Hebrew)

एस्पिरि (hindi)

阿司匹林 (Chinese)

ア セ チ ル サ リ チ ル ル (Japanese)

Many thanks!

+4
source share
1 answer

This is not the serializer causing this problem; Json.Net does a great job with foreign characters. Most likely, you will do one of the following:

  • ( ) JSON . , Encoding.UTF8.
  • JSON varchar , nvarchar. varchar Unicode.
  • JSON , , / , . Windows, , , .

, , . JSON, UTF-8, . . "default" ? . UTF-8 , . ( , "" "Arial Unicode MS".)

, JSON Visual Studio; , JSON json.

using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

class Program
{
    static void Main(string[] args)
    {
        List<Foo> foos = new List<Foo>
        {
            new Foo { Language = "Hebrew", Sample = "אספירין" },
            new Foo { Language = "Hindi", Sample = "एस्पिरि" },
            new Foo { Language = "Chinese", Sample = "阿司匹林" },
            new Foo { Language = "Japanese", Sample = "アセチルサリチル酸" },
        };

        var json = JsonConvert.SerializeObject(foos, Formatting.Indented);

        File.WriteAllText("utf8.json", json, Encoding.UTF8);
        File.WriteAllText("default.json", json, Encoding.Default);
    }
}

class Foo
{
    public string Language { get; set; }
    public string Sample { get; set; }
}
+6

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


All Articles