最近整理了一些C# JSON的处理方法,大致如下:
1—创建json对象
2—创建json数组
3—查询
4—修改
5—删除
6—添加
7—简化查询
8—删除列表里的a节点的值为aa的项
9—json其它用法
:::info
注意:使用该方法的时候需引用Newtonsoft.Json库文件,请在官网(http://www.newtonsoft.com/json)下载
:::
以上是整理的一些常用JSON处理方法,后续将继续补充!
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; //StringReader
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;//IsoDateTimeConverter
namespace json1
{
class Program
{
static void Main(string[] args)
{
#region 创建json对象
Console.WriteLine("\n\n1--创建json对象:");
JObject staff = new JObject();
staff.Add(new JProperty("Name", "Jack"));//等价于staff.Add("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());
#endregion
#region 创建json数组
Console.WriteLine("\n\n2--创建json数组:");
JArray arr = new JArray();
arr.Add(new JValue(1));
arr.Add(new JValue(2));
arr.Add(new JValue(3));
Console.WriteLine(arr.ToString());
#endregion
#region 查询
Console.WriteLine("\n\n3--查询:");
string json3 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
//将json转换为JObject
JObject jObj = JObject.Parse(json3);
#region 查询-获取某一员工的年龄
Console.WriteLine("获取某一员工的年龄:");
//通过属性名或者索引来访问,仅仅是自己的属性名,而不是所有的
JToken ageToken = jObj["Age"];
Console.WriteLine("age:" + ageToken.ToString());
#endregion
#region 查询-获取该员工所有同事的姓名
Console.WriteLine("获取该员工所有同事的姓名:");
var names = from staff1 in jObj["Colleagues"].Children()
select (string)staff1["Name"];
//"Children()"可以返回所有数组中的对象
foreach (var name in names)
Console.WriteLine(name);
#endregion
#endregion
#region 修改
Console.WriteLine("\n\n4--修改:");
string json4 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
//将json转换为JObject
JObject jObj4 = JObject.Parse(json4);
#region 修改--将jack年龄修改为35
Console.WriteLine("修改--将jack年龄修改为35");
jObj4["Age"] = 35;
//JToken age =
Console.WriteLine(jObj4.ToString());
#endregion
#region 修改--将jack同事tom年龄修改Wie45
Console.WriteLine("\n修改--将jack同事tom年龄修改为45");
JToken colleagues = jObj4["Colleagues"];//JToken 不用实例化
colleagues[0]["Age"] = 45;
jObj4["Colleagues"] = colleagues;//将修改后的赋值给json对象
Console.WriteLine(jObj4.ToString());
#endregion
#endregion
#region 删除
Console.WriteLine("\n\n5--删除:");
string json5 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29},{\"Name\" : \"Jully\",\"Age\":23}] }";
//将json转换为JObject
JObject jObj5 = JObject.Parse(json5);
#region 删除--删除同事Tom
Console.WriteLine("删除--删除同事Tom");
jObj5["Colleagues"][0].Remove();
Console.WriteLine(jObj5.ToString());
#endregion
#region 删除--删除所有同事
Console.WriteLine("\n删除--删除所有同事");
jObj5.Remove("Colleagues");//跟的是属性名称
Console.WriteLine(jObj5.ToString());
#endregion
#endregion
#region 添加
Console.WriteLine("\n\n6--添加:");
string json6 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29},{\"Name\" : \"Jully\",\"Age\":23}] }";
//将json转换为JObject
JObject jObj6 = JObject.Parse(json6);
#region 发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面
Console.WriteLine("发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面");
jObj6["Age"].Parent.AddAfterSelf(new JProperty("Department", "Personnel Department"));
Console.WriteLine(jObj6.ToString());
#endregion
#region 添加一个新同事
Console.WriteLine("\n添加一个新同事");
JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23"));
jObj6["Colleagues"].Last.AddAfterSelf(linda);
Console.WriteLine(jObj6.ToString());
#endregion
#endregion
#region 简化查询
Console.WriteLine("\n\n7--简化查询:");
string json7 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29},{\"Name\" : \"Jully\",\"Age\":23}] }";
//将json转换为JObject
JObject jObj7 = JObject.Parse(json7);
#region 利用SelectToken来查询名称
Console.WriteLine("简化查询--利用SelectToken来查询名称");
JToken name7 = jObj7.SelectToken("Name");
Console.WriteLine(name7.ToString());
#endregion
#region 简化查询--利用SelectToken来查询所有同事的名字
Console.WriteLine("\n简化查询--利用SelectToken来查询所有同事的名字");
var names7 = jObj7.SelectToken("Colleagues").Select(p => p["Name"]).ToList();
foreach (var theName in names7)
Console.WriteLine(theName.ToString());
#endregion
#region 简化查询--查询最后一名同事的年龄
Console.WriteLine("\n简化查询--查询最后一名同事的年龄");
var age = jObj7.SelectToken("Colleagues[2].Age");
Console.WriteLine(age.ToString());
#endregion
#endregion
#region 删除列表里a节点的值为aa的项
Console.WriteLine("\n\n8--删除列表里的a节点的值为aa的项:");
string jsonText = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb','c':'cc'}]";
var mJObj8 = JArray.Parse(jsonText);
string str1 = mJObj8.ToString();
Console.WriteLine("before delete:\n" + str1);
IList<JToken> delList = new List<JToken>(); //存储需要删除的项
foreach (var ss in mJObj8) //查找某个字段与值
{
if (((JObject)ss)["a"].ToString() == "aa")
delList.Add(ss);
}
foreach (var item in delList) //移除mJObj 在delList 里的项
{
mJObj8.Remove(item);
}
string str2 = mJObj8.ToString();
Console.WriteLine("after delete:\n" + str2);
#endregion
#region json其它用法
Console.WriteLine("\n\n9--json其它用法:");
string jsonStr9_1 = @"
[{'Languages':['C#','Java'],'Name':'李志伟','Sex':true},
{'Languages':['C#','C++'],'Name':'Coder2','Sex':false},
{'Languages':['C#','C++','C','Java'],'Name':'Coder3','Sex':true}]";
Console.WriteLine(jsonStr9_1);
#region 使用JsonTextReader类进行只进读取(不常用)
Console.WriteLine("\n9_1--使用JsonTextReader类进行只进读取:");
JsonTextReader json1 = new JsonTextReader(new StringReader(jsonStr9_1));
while (json1.Read())
{
Console.WriteLine(json1.Value + "--" + json1.TokenType + "--" + json1.ValueType);
}
#endregion
#region 使用JArray、JObject、JToken进行读取(常用)
Console.WriteLine("\n9_2--使用JArray、JObject、JToken进行读取:");
string jsonStr9_2 = @"
[{'Languages':['C#','Java'],'Name':'李志伟','Sex':true},
{'Languages':['C#','C++'],'Name':'Coder2','Sex':false},
{'Languages':['C#','C++','C','Java'],'Name':'Coder3','Sex':true}]";
var Jobj = JArray.Parse(jsonStr9_2);
string mystr1 = Jobj.ToString();
Console.WriteLine("this json:\n" + mystr1);
JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr9_2);
foreach (JToken jt in ja)
{
JObject jo = (JObject)jt;
JArray temp = (JArray)jo["Languages"];
foreach (JToken token in temp)
{
Console.Write(token + " ");
}
Console.WriteLine("\t" + jo["Name"] + "\t" + jo["Sex"]);
}
#endregion
#region Json时间字符串的处理
Console.WriteLine("\nJson9_3--时间字符串的处理:");
DateTime time = DateTime.Now;
//这里使用自定义日期格式
IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
timeConverter.DateTimeFormat = "北京时间:yyyy-MM-dd HH:mm:ss";
//序列化时间
string JsonStr = JsonConvert.SerializeObject(time, timeConverter);
Console.WriteLine(JsonStr);
//反序列化时间
DateTime time2 = JsonConvert.DeserializeObject<DateTime>(JsonStr, timeConverter);
Console.WriteLine(time2);
Console.WriteLine("\n\n");
#endregion
#endregion
}
}
}