Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize special characters with JsonSerializing

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 = "";

         }
like image 955
saulyasar Avatar asked May 18 '18 10:05

saulyasar


People also ask

Can you serialize a list in JSON?

Can JSON serialize a list? Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.

Can you serialize tuples?

Summary. Class Foo with Tuple data, can be serialized to json string, and the string can be deserialized back to Class Foo .

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json.


2 Answers

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.

like image 93
Martin Liversage Avatar answered Sep 26 '22 16:09

Martin Liversage


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.

like image 32
Fabian T. Avatar answered Sep 26 '22 16:09

Fabian T.