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

我需要编写一个称为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()and解决这个问题之前Regex.Replace(),是否有某种更简单的 JSON 字符串到数组转换器可以使用,或者将带有字符串的序列化 JSON 字符串转换为带有字符串的序列化 JSON 字符串的最简单方法是什么?数组?


慕运维8079593
浏览 195回答 2
2回答

噜噜哒

您应该为此使用一些 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{&nbsp; &nbsp;{"To", JArray.FromObject(to)},&nbsp; &nbsp;{"CC", JArray.FromObject(cc)},&nbsp; &nbsp;{"BCC", JArray.FromObject(bcc)},});请注意,没有错误处理。例如,如果原始字符串错过了三个列表之一,这将抛出。

倚天杖

使用 Newtonsoft.Jsonstring strJson = @"{'To':'name @company.com, name2 @company.com, name3 @company.com','CC':'namecc @company.com','BCC':''}";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dynamic jsonObject = JsonConvert.DeserializeObject(strJson);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Dictionary<string, string[]> val = new Dictionary<string, string[]>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (var prop in jsonObject)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string name = prop.Name;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string[] datas = Convert.ToString(prop.Value).Split(',');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; val.Add(name, datas);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string op = JsonConvert.SerializeObject(val);
打开App,查看更多内容
随时随地看视频慕课网APP