使用Newtonsoft.Json创建JSON对象
参考链接:https://blog.csdn.net/chentiebo/article/details/130383788
一、创建JSON对象
JObject staff = new JObject();
staff.Add(new JProperty("Name", "Jack"));
staff.Add(new JProperty("Age", 33));
staff.Add(new JProperty("Department", "Personnel Department"));
staff.Add(new JProperty("Leader", new JObject(new JProperty("Name", "Tom"), new JProperty("Age", 44), new JProperty("Department", "Personnel Department"))));
Console.WriteLine(staff.ToString());
二、创建JSON数组
// 创建数组
JArray array = new JArray();
array.Add(new JValue("吃饭"));
array.Add(new JValue("睡觉"));
obj.Add("Favorites", array);
obj.Add("Remark", null);
Console.WriteLine(array.ToString());
上面代码可以简化成:
JArray array = new JArray("吃饭", "睡觉");
C#将Dictionary字典集合转换为json字符串
参考链接:https://blog.csdn.net/qq15577969/article/details/129379842
注意:需要引用Newtonsoft.Json.dll库(请自行下载对应的版本)
1、把Dictionary集合转换为json字符串
Dictionary<int, string> dicList = new Dictionary<int, string>();
string json = JsonConvert.SerializeObject(dicList);
2、把json字符串转换为Dictionary集合
Dictionary<int, string> dicList = JsonConvert.DeserializeObject<Dictionary<int, string>>(json);