class="MsoNormal" style="text-align: center;" align="center">C#操作JSON
1. .NET对JSON的支持介绍....................................................... 1
(1) 操作Json的DLL介绍..................................................... 1
(2) 使用System.Web.Extensions.dll的限制............... 1
2. JSON序列化和反序列化.......................................................... 1
(1) 使用Newtonsoft.Json.dll实现................................. 1
(2) 使用System.Web.Extensions.dll实现.................... 2
(3) 使用System.Runtime.Serialization.dll实现.... 3
(4) 小结..................................................................................... 5
3. 解析JSON字符串(使用Newtonsoft.Json.dll).............. 5
(1) 使用JsonTextReader类进行只进读取(不常用)...... 5
(2) 使用JArray、JObject、JToken进行读取(常用)... 5
(3) Json时间字符串的处理.................................................. 6
4. 读取Json字符串的技巧......................................................... 6
(1) 使用匿名类........................................................................ 6
(2) 使用索引器........................................................................ 6
1..NET对JSON的支持介绍
(1)操作Json的DLL介绍
.NET自身有System.Runtime.Serialization.dll与System.Web.Extensions.dll,使用这两个DLL可以把对象序列化和反序列化成Json数据。
也可以使用第三方的Newtonsoft.Json.dll来操作Json数据,使用它会更方便的操作Json数据,其功能也跟强一些。下载地址:http://json.codeplex.com/
(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();
}
}
得到的Json文本:
[{"姓名":"李志伟","性别":true,"编程语言":["C#","Java"]},
{"姓名":"Coder2","性别":false,"编程语言":["C#","C++"]},
{"姓名":"Coder3","性别":true,"编程语言":["C#","C++","C","Java"]}]
注意:此种方式Json序列化对象时,可以序列化对象的任意成员(包括私有成员),但是使用此方式必须要在类和成员的定义处加上相应的特性(具体请参考代码)。
(4)小结
使用的DLL
序列化范围
项目范围
依赖构造器
依赖特性
Newtonsoft.Json.dll
公有成员
任意项目
否
否
System.Web.Extensions.dll
公有成员
Web项目
无参构造器
否
System.Runtime.Serialization.dll
所有成员
任意项目
否
是
3.解析JSON字符串(使用Newtonsoft.Json.dll)
(1)使用JsonTextReader类进行只进读取(不常用)
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();
}
}