首页 > 解决方案 > 如何使用 JsonSerializing 序列化特殊字符

问题描述

我有一个带有塞尔维亚字符的 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 = "";

         }

标签: c#.netjsonserializationjson.net

解决方案


尽管这个线程现在已经很老了,但我会尝试帮助一些在我之后偶然发现这个线程的人。我真的不明白这个线程的主要问题或意图,但我认为 saulyasar 错误地表达了他的问题。我将他的问题解释为:如何将字符串“Željko Cvijetić”序列化为 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 编码器解决了这个问题。


推荐阅读