《JSON篇》使用Newtonsoft.Json创建JSON对象
使用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>();
dicList.Add("xm", "tom");//姓名
string json = JsonConvert.SerializeObject(dicList);
2、把json字符串转换为Dictionary集合
Dictionary<int, string> dicList = JsonConvert.DeserializeObject<Dictionary<int, string>>(json);
注意:Dictionary的键不能重复Add,需要换成Hashtable
参考链接:https://zhidao.baidu.com/question/2079542286495408268.html
Hashtable使用方式
参考链接:https://blog.csdn.net/weixin_50233101/article/details/119151780
1、使用
using System;
using System.Collections; //使用Hashtable时,必须引入这个命名空间
class hashtable
{
public static void Main()
{
Hashtable ht=new Hashtable(); //创建一个Hashtable实例
ht.Add("E","e");//添加keyvalue键值对
ht.Add("A","a");
ht.Add("C","c");
ht.Add("B","b");
string s=(string)ht["A"];
if(ht.Contains("E")) //判断哈希表是否包含特定键,其返回值为true或false
Console.WriteLine("the E key exist");
ht.Remove("C");//移除一个keyvalue键值对
Console.WriteLine(ht["A"]);//此处输出a
ht.Clear();//移除所有元素
Console.WriteLine(ht["A"]); //此处将不会有任何输出
}
}
2、遍历
for(DictionaryEntry de in ht) //ht为一个Hashtable实例
{
Console.WriteLine(de.Key);//de.Key对应于keyvalue键值对key
Console.WriteLine(de.Value);//de.Key对应于keyvalue键值对value
}

浙公网安备 33010602011771号