gpt4 book ai didi

c# - 如何最轻松地将带字符串的 JSON 转换为带数组的 JSON?

转载 作者:行者123 更新时间:2023-11-30 21:33:05 24 4
gpt4 key购买 nike

我需要编写一个名为 public string PrepareForDeserialization(string json) 的方法来转换 JSON 字符串,如下所示:

{"To":"name@company.com, name2@company.com, name3@company.com","CC":"namecc@company.com","BCC":""}

像这样的 JSON 字符串:

{"To":["name@company.com", "name2@company.com", "name3@company.com"],"CC":["namecc@company.com"],"BCC":[]}

在我开始使用 Substring()Regex.Replace() 解决这个问题之前,是否有某种更简单的 JSON 字符串到数组转换器可以使用,或者将带字符串的序列化 JSON 字符串转换为带数组的序列化 JSON 字符串的最简单方法是什么?

最佳答案

您应该为此使用一些 JSON 库(例如 Json.net)。在手动操作 JSON 字符串时,这将解决许多您可能会错过的陷阱。

var o1 = JsonConvert.Deserialize<JObject>(jsonstring);

//you can split by ' ' and ',' because email addresses won't contain any whitespaces. For other purposes you may need better splitting rules.
var to = o1.Value<string>("To").Split(new char[]{' ', ',"}, StringSplitOptions.RemoveEmptyEntries);
var cc = o1.Value<string>("CC").Split(new char[]{' ', ',"}, StringSplitOptions.RemoveEmptyEntries);
var bcc = o1.Value<string>("BCC").Split(new char[]{' ', ',"}, StringSplitOptions.RemoveEmptyEntries);
var outstring = JsonConvert.SerializeObject(new JObject{
{"To", JArray.FromObject(to)},
{"CC", JArray.FromObject(cc)},
{"BCC", JArray.FromObject(bcc)},
});

注意,没有错误处理。例如,如果原始字符串缺少三个列表之一,这将抛出。

关于c# - 如何最轻松地将带字符串的 JSON 转换为带数组的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51767874/

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