c# - 如何使用 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 = "";
}
解决方案
尽管这个线程现在已经很老了,但我会尝试帮助一些在我之后偶然发现这个线程的人。我真的不明白这个线程的主要问题或意图,但我认为 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 编码器解决了这个问题。
推荐阅读
- swift - iOS 13 isKeyWindow 总是返回 nil
- python - 在 Pytorch 中实现 LeNet
- c++ - c++:struct和decltype比较器的priority_queue
- zsh - Zsh glob:子目录下的对象递归,不包括当前/基本目录
- python - 使用嵌套的 defaultdict 重新分配 pandas 系列值
- python - 在 Python 中搜索数组以获取精确匹配
- batch-file - 使用批处理文件在特定路径中运行所有带有参数的 exe 文件
- sparql - 如何使用正则表达式过滤日期以在 sparql 中获取电影发行日期
- python - 为什么分类器链要求至少 2 个类,当我有它时
- excel - 范围中的下一个非空白单元格