How to serialize special characters with JsonSerializing

12,895

Solution 1

Altough this thread is quite old by now I'll try to help some people that stumble across this thread after me. I dont really understand the main problem or intention of this thread but I think saulyasar misformulated his question. I'll interpret his question as: How can I serialize my string "Željko Cvijetić" into JSON without the characters being converted to something like "}\u0001".

The answer to this is quite simple:

var output = JsonSerializer.Serialize("Željko Cvijetić", new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = JavaScriptEncoder.Default
                });

-> output: "\"\\u017Deljko Cvijeti\\u0107\""

converts the string to JSON but converts the special characters, while

var output = JsonSerializer.Serialize("Željko Cvijetić", new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                });

-> output: "\"Željko Cvijetić\""

solves the problem by using the UnsafeRelaxedJsonEscaping Encoder.

Solution 2

JSON supports Unicode and JSON will normally be encoded as UTF-8 when used in an HTTP API. However, if you need to escape non-ASCII characters when serializing to JSON you can specify that using the JsonSerializerSettings.StringEscapeHandling property:

var text = "Željko Cvijetić";
var jsonSerializerSettings = new JsonSerializerSettings {
    StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};
var json = JsonConvert.SerializeObject(text, jsonSerializerSettings);

This results in this JSON:

"\u017deljko Cvijeti\u0107"

This is not the same as you show in your question but to be honest I have no idea how Ž maps to "}\u0001". Please see Unicode escape sequences for how to escape a character in a JavaScript string literal.

Share:
12,895
saulyasar
Author by

saulyasar

I'm a web developer . I like to use .net and telerik components

Updated on June 06, 2022

Comments

  • saulyasar
    saulyasar almost 2 years

    I have a json data with Serbian Characters! When i want to get this data i need JsonSeriaize and data transform for example Željko Cvijetić To }\u0001eljko Cvijeti\u0007\u0001

    Do you have any idea to solve this problem?

    Here i have Json Result example

    "SMSFlowMessages": [
    {
      "Display": "Example",
      "MessageId": 104,
      "MessageText": "Dear }\u0001eljko Cvijeti\u0007\u0001, the 22-05-2018 it will be your Birthday!!\nIn this special day you will have double points on all products!\n\nExample Team"
    },
    {
      "Display": "Example",
      "MessageId": 105,
      "MessageText": "Dear test test, the 22-05-2035 it will be your Birthday!!\nIn this special day you will have double points on all products!\n\nExample Team"
    },
    

    Here my C# Code

      JsonSerializerSettings settings = new JsonSerializerSettings() { Culture = new CultureInfo("sr-Latn-CS") };
        json = JsonConvert.SerializeObject(root, settings);
    
         root.SMSFlowMessages.Clear();
         root.ViberFlowMessages.Clear();
    
          try
          {
    
          log.append("SMS SEND>>START:" + Environment.NewLine + json + Environment.NewLine + ">>END", logdir);
    
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(apiurl);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            var getresult = client.PostAsync(apiurl, stringContent).Result;
            string resultContent = getresult.Content.ReadAsStringAsync().Result;
            log.append("SMS RECV<<START:" + Environment.NewLine + resultContent + Environment.NewLine + "<<END", logdir);
    
             smsflag = "";
             json = "";
    
             }
    
    • Zelleriation
      Zelleriation almost 6 years
      You need to convert your text before JSONing it. Take a look at this: stackoverflow.com/questions/1615559/…
    • gnud
      gnud almost 6 years
      Why does Ž turn into }\u0001? What weird encoding scheme is this?
  • Cleiton Tortato
    Cleiton Tortato over 2 years
    Old answer here, but is the right way and works with strings serialized on cookies too. Thanks