如何使用JsonSerializing序列化特殊字符

时间:2018-05-18 10:28:19

标签: c# .net json serialization json.net

我有塞尔维亚人物的json数据!当我想获得这些数据时,我需要JsonSeriaize和数据转换,例如Željko Cvijetić}\u0001eljko Cvijeti\u0007\u0001

你有什么想法解决这个问题吗?

这里我有Json结果示例

"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"
},

这是我的C#代码

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

         }

2 个答案:

答案 0 :(得分:6)

尽管此线程现在已经很老了,我会尽力帮助一些在我之后偶然发现此线程的人。 我不太了解此主题的主要问题或意图,但我认为saulyasar歪曲了他的问题。我将他的问题解释为:如何将我的字符串“ŽeljkoCvijetić”序列化为JSON,而又不将这些字符转换为类似“} \ u0001”的字符。

答案很简单:

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

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

将字符串转换为JSON,但转换特殊字符,而

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

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

通过使用UnsafeRelaxedJsonEscaping编码器解决了该问题。

答案 1 :(得分:3)

JSON支持Unicode,当在HTTP API中使用时,JSON通常会被编码为UTF-8。但是,如果在序列化为JSON时需要转义非ASCII字符,则可以使用JsonSerializerSettings.StringEscapeHandling属性指定:

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

这导致了这个JSON:

"\u017deljko Cvijeti\u0107"

这与你在问题中显示的不一样,但说实话我不知道如何映射到"}\u0001"。有关如何转义JavaScript字符串文字中的字符,请参阅Unicode escape sequences