《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
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?