欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

c#操作json示例分享

时间:2022-08-30 09:29:47|栏目:.NET代码|点击:

1..NET对JSON的支持介绍

(1)操作Json的DLL介绍

.NET自身有System.Runtime.Serialization.dll与System.Web.Extensions.dll,使用这两个DLL可以把对象序列化和反序列化成Json数据。也可以使用第三方的Newtonsoft.Json.dll来操作Json数据,使用它会更方便的操作Json数据,其功能也跟强一些。

(2)使用System.Web.Extensions.dll的限制

要使用System.Web.Extensions.dll必须是在Web项目中,只有在Web项目中才能引用此DLL。

2.JSON序列化和反序列化

(1)使用Newtonsoft.Json.dll实现

代码示例:

复制代码 代码如下:

public class Person
{
public string Name;//姓名
public bool Sex;//性别,是否是男
public Person(string name, bool sex)
{
this.Name = name;
this.Sex = sex;
}
public override string ToString()
{
return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");
}
}
public class Programmer : Person
{
public List<string> Languages;//编程语言
public Programmer(string name, bool sex, List<string> languages) : base(name, sex)
{
this.Languages = languages;
}
public override string ToString()
{
StringBuilder str = new StringBuilder();
str.Append(base.ToString() + "\t编程语言:");
foreach (string l in this.Languages)
{
str.Append(l + " ");
}
return str.ToString();
}
}
class Program
{
static void Main(string[] args)
{
string filePath = @"D:\users\lizw\桌面\ObjectJson.txt";
List<string> languages = null;
List<Programmer> list = new List<Programmer>();
languages = new List<string>(new string[] { "C#", "Java" });
list.Add(new Programmer("李志伟", true, languages));
languages = new List<string>(new string[] { "C#", "C++" });
list.Add(new Programmer("Coder2", false, languages));
languages = new List<string>(new string[] { "C#", "C++", "C", "Java" });
list.Add(new Programmer("Coder3", true, languages));
//序列化对象
string jsonStr = JsonConvert.SerializeObject(list);//将对象转换成json存储
File.WriteAllText(filePath, jsonStr);
list.Clear();
//反序列化对象
list = JsonConvert.DeserializeObject<List<Programmer>>(jsonStr);
foreach (Programmer p in list)
{
Console.WriteLine(p);
}
Console.WriteLine("OK!");
Console.Read();
}
}

得到的Json文本:

[{"Languages":["C#","Java"],"Name":"李志伟","Sex":true},

{"Languages":["C#","C++"],"Name":"Coder2","Sex":false},

{"Languages":["C#","C++","C","Java"],"Name":"Coder3","Sex":true}]

注意:此种方式Json序列化对象时,只能序列化对象的公有成员。

(2)使用System.Web.Extensions.dll实现

代码示例:

复制代码 代码如下:

public class Person

{

public string Name;//姓名

public bool Sex;//性别,是否是男

public Person() { }//必须有此构造方法,否者无法反序列化

public Person(string name, bool sex)

{

this.Name = name;

this.Sex = sex;

}

public override string ToString()

{

return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");

}

}

public class Programmer : Person

{

public List<string> Languages;//编程语言

public Programmer() { }//必须有此构造方法,否者无法反序列化

public Programmer(string name, bool sex, List<string> languages)

: base(name, sex)

{

this.Languages = languages;

}

public override string ToString()

{

StringBuilder str = new StringBuilder();

str.Append(base.ToString() + "\t编程语言:");

foreach (string l in this.Languages)

{

str.Append(l + " ");

}

return str.ToString();

}

}

public partial class WebForm1 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)//Web页面的加载事件

{

List<string> languages = null;

List<Programmer> list = new List<Programmer>();

languages = new List<string>(new string[] { "C#", "Java" });

list.Add(new Programmer("李志伟", true, languages));

languages = new List<string>(new string[] { "C#", "C++" });

list.Add(new Programmer("Coder2", false, languages));

languages = new List<string>(new string[] { "C#", "C++", "C", "Java" });

list.Add(new Programmer("Coder3", true, languages));

//序列化对象

JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();

string jsonStr = jsonSerialize.Serialize(list);//将对象转换成json存储

Response.Write(jsonStr + "<br>");//前台输出

//反序列化对象

list.Clear();

list = jsonSerialize.Deserialize<List<Programmer>>(jsonStr);

foreach (Programmer p in list)

{

Response.Write(p + "<br>");//前台输出

}

}

}

得到的Json文本:

[{"Languages":["C#","Java"],"Name":"李志伟","Sex":true},

{"Languages":["C#","C++"],"Name":"Coder2","Sex":false},

{"Languages":["C#","C++","C","Java"],"Name":"Coder3","Sex":true}]

注意:此种方式Json序列化对象时,除了只能序列化对象的公有成员外,被序列化的对象还必须有无参的构造方法才能被反序列化!System.Web.Extensions.dll只能在Web项目中引用,在控制台和WinFrom项目中无法引用!

(3)使用System.Runtime.Serialization.dll实现

代码示例:

复制代码 代码如下:

[DataContract]//必须申明,否则无法序列化

public class Person

{

[DataMember(Name = "姓名")]//必须申明,否则无法序列化

private string Name;

[DataMember(Name = "性别")]//必须申明,否则无法序列化

private bool Sex;

public Person(string name, bool sex)

{

this.Name = name;

this.Sex = sex;

}

public override string ToString()

{

return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");

}

}

[DataContract]

public class Programmer : Person

{

[DataMember(Name = "编程语言")]

private List<string> Languages;

public Programmer(string name, bool sex, List<string> languages)

: base(name, sex)

{

this.Languages = languages;

}

public override string ToString()

{

StringBuilder str = new StringBuilder();

str.Append(base.ToString() + "\t编程语言:");

foreach (string l in this.Languages)

{

str.Append(l + " ");

}

return str.ToString();

}

}

class Program

{

static void Main(string[] args)

{

string filePath = @"D:\users\lizw\桌面\ObjectJson.txt";

List<string> languages = null;

List<Programmer> list = new List<Programmer>();

languages = new List<string>(new string[] { "C#", "Java" });

list.Add(new Programmer("李志伟", true, languages));

languages = new List<string>(new string[] { "C#", "C++" });

list.Add(new Programmer("Coder2", false, languages));

languages = new List<string>(new string[] { "C#", "C++", "C", "Java" });

list.Add(new Programmer("Coder3", true, languages));

//序列化对象

DataContractJsonSerializer ser =

new DataContractJsonSerializer(typeof(List<Programmer>));

MemoryStream ms = new MemoryStream();

ser.WriteObject(ms, list);//将对象转换成json存储

string jsonStr = Encoding.UTF8.GetString(ms.ToArray());

File.WriteAllText(filePath, jsonStr);

//反序列化对象

list.Clear();

ms.Position = 0;

list = (List<Programmer>)ser.ReadObject(ms);

foreach (Programmer p in list)

{

Console.WriteLine(p);

}

ms.Dispose();//关闭内存流

Console.WriteLine("OK!");

Console.Read();

}

}
[code]

得到的Json文本:

[{"姓名":"李志伟","性别":true,"编程语言":["C#","Java"]},

{"姓名":"Coder2","性别":false,"编程语言":["C#","C++"]},

{"姓名":"Coder3","性别":true,"编程语言":["C#","C++","C","Java"]}]

注意:此种方式Json序列化对象时,可以序列化对象的任意成员(包括私有成员),但是使用此方式必须要在类和成员的定义处加上相应的特性(具体请参考代码)。

(4)小结

3.解析JSON字符串(使用Newtonsoft.Json.dll)

(1)使用JsonTextReader类进行只进读取(不常用)
[code]
class Program

{

static void Main(string[] args)

{

//Json字符串

string jsonStr = @"

[{'Languages':['C#','Java'],'Name':'李志伟','Sex':true},

{'Languages':['C#','C++'],'Name':'Coder2','Sex':false},

{'Languages':['C#','C++','C','Java'],'Name':'Coder3','Sex':true}]";

JsonTextReader json = new JsonTextReader(new StringReader(jsonStr));

while (json.Read())

{

Console.WriteLine(json.Value + "--" + json.TokenType + "--" + json.ValueType);

}

Console.WriteLine("OK!");

Console.Read();

}

}

(2)使用JArray、JObject、JToken进行读取(常用)

复制代码 代码如下:

class Program

{

static void Main(string[] args)

{

//Json字符串

string jsonStr = @"

[{'Languages':['C#','Java'],'Name':'李志伟','Sex':true},

{'Languages':['C#','C++'],'Name':'Coder2','Sex':false},

{'Languages':['C#','C++','C','Java'],'Name':'Coder3','Sex':true}]";

JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr);

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"]);

}

Console.WriteLine("OK!");

Console.Read();

}

}

(3)Json时间字符串的处理

复制代码 代码如下:

class Program

{

static void Main(string[] args)

{

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("OK!");

Console.Read();

}

}

4.读取Json字符串的技巧

(1)使用匿名类

复制代码 代码如下:

class Program

{

static void Main(string[] args)

{

//Json字符串

string jsonStr = @"{'Languages':['C#','Java'],'Name':'李志伟','Sex':true}";

//创建匿名类

var TempClass = new { Languages = new string[0], Name = string.Empty, Sex = false };

//反序列化

var O = JsonConvert.DeserializeAnonymousType(jsonStr, TempClass);

Console.WriteLine(O.Name+"\t"+O.Sex+"\t"+O.Languages[1]);

Console.Read();

}

}

(2)使用索引器

复制代码 代码如下:

class Program

{

static void Main(string[] args)

{

//Json字符串

string jsonStr = @"{'Languages':['C#','Java'],'Name':'李志伟','Sex':true}";

//反序列化

JObject O = JsonConvert.DeserializeObject(jsonStr) as JObject;

//使用索引器访问

Console.WriteLine(O["Name"] + "\t" + O["Sex"] + "\t" + O["Languages"][1]);

Console.Read();

}
}

上一篇:.NET的file文件上传控件使用方法 修改web.config文件上传大文件

栏    目:.NET代码

下一篇:C#图表算法之最短路径

本文标题:c#操作json示例分享

本文地址:http://www.codeinn.net/misctech/212299.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有