gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:14 25 4
gpt4 key购买 nike

我有一个带有塞尔维亚字符的 json 数据!当我想获取此数据时,我需要 JsonSeriaize 和数据转换,例如 Željko Cvijetić To }\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 = "";

}

最佳答案

虽然这个线程现在已经很老了,但我会尽力帮助一些在我之后偶然发现这个线程的人。我真的不明白这个线程的主要问题或意图,但我认为 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 编码器解决了这个问题。

关于c# - 如何使用 JsonSerializing 序列化特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50409273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com