码迷,mamicode.com
首页 > Windows程序 > 详细

10.C#操作JSON

时间:2015-03-05 20:45:42      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

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实现
    代码示例:
  1. public class Person
  2. {
  3. public string Name;//姓名
  4. public bool Sex;//性别,是否是男
  5. public Person(string name, bool sex)
  6. {
  7. this.Name = name;
  8. this.Sex = sex;
  9. }
  10. public override string ToString()
  11. {
  12. return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");
  13. }
  14. }
  15. public class Programmer : Person
  16. {
  17. public List<string> Languages;//编程语言
  18. public Programmer(string name, bool sex, List<string> languages) : base(name, sex)
  19. {
  20. this.Languages = languages;
  21. }
  22. public override string ToString()
  23. {
  24. StringBuilder str = new StringBuilder();
  25. str.Append(base.ToString() + "\t编程语言:");
  26. foreach (string l in this.Languages)
  27. {
  28. str.Append(l + " ");
  29. }
  30. return str.ToString();
  31. }
  32. }
  33. class Program
  34. {
  35. static void Main(string[] args)
  36. {
  37. string filePath = @"D:\users\lizw\桌面\ObjectJson.txt";
  38. List<string> languages = null;
  39. List<Programmer> list = new List<Programmer>();
  40. languages = new List<string>(new string[] { "C#", "Java" });
  41. list.Add(new Programmer("李志伟", true, languages));
  42. languages = new List<string>(new string[] { "C#", "C++" });
  43. list.Add(new Programmer("Coder2", false, languages));
  44. languages = new List<string>(new string[] { "C#", "C++", "C", "Java" });
  45. list.Add(new Programmer("Coder3", true, languages));
  46. //序列化对象
  47. string jsonStr = JsonConvert.SerializeObject(list);//将对象转换成json存储
  48. File.WriteAllText(filePath, jsonStr);
  49. list.Clear();
  50. //反序列化对象
  51. list = JsonConvert.DeserializeObject<List<Programmer>>(jsonStr);
  52. foreach (Programmer p in list)
  53. {
  54. Console.WriteLine(p);
  55. }
  56. Console.WriteLine("OK!");
  57. Console.Read();
  58. }
  59. }
    得到的Json文本:
  1. [{"Languages":["C#","Java"],"Name":"李志伟","Sex":true},
  2. {"Languages":["C#","C++"],"Name":"Coder2","Sex":false},
  3. {"Languages":["C#","C++","C","Java"],"Name":"Coder3","Sex":true}]
    注意:此种方式Json序列化对象时,只能序列化对象的公有成员。
(2)使用System.Web.Extensions.dll实现
    代码示例:
  1. public class Person
  2. {
  3. public string Name;//姓名
  4. public bool Sex;//性别,是否是男
  5. public Person() { }//必须有此构造方法,否者无法反序列化
  6. public Person(string name, bool sex)
  7. {
  8. this.Name = name;
  9. this.Sex = sex;
  10. }
  11. public override string ToString()
  12. {
  13. return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");
  14. }
  15. }
  16. public class Programmer : Person
  17. {
  18. public List<string> Languages;//编程语言
  19. public Programmer() { }//必须有此构造方法,否者无法反序列化
  20. public Programmer(string name, bool sex, List<string> languages)
  21. : base(name, sex)
  22. {
  23. this.Languages = languages;
  24. }
  25. public override string ToString()
  26. {
  27. StringBuilder str = new StringBuilder();
  28. str.Append(base.ToString() + "\t编程语言:");
  29. foreach (string l in this.Languages)
  30. {
  31. str.Append(l + " ");
  32. }
  33. return str.ToString();
  34. }
  35. }
  36. public partial class WebForm1 : System.Web.UI.Page
  37. {
  38. protected void Page_Load(object sender, EventArgs e)//Web页面的加载事件
  39. {
  40. List<string> languages = null;
  41. List<Programmer> list = new List<Programmer>();
  42. languages = new List<string>(new string[] { "C#", "Java" });
  43. list.Add(new Programmer("李志伟", true, languages));
  44. languages = new List<string>(new string[] { "C#", "C++" });
  45. list.Add(new Programmer("Coder2", false, languages));
  46. languages = new List<string>(new string[] { "C#", "C++", "C", "Java" });
  47. list.Add(new Programmer("Coder3", true, languages));
  48. //序列化对象
  49. JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
  50. string jsonStr = jsonSerialize.Serialize(list);//将对象转换成json存储
  51. Response.Write(jsonStr + "<br>");//前台输出
  52. //反序列化对象
  53. list.Clear();
  54. list = jsonSerialize.Deserialize<List<Programmer>>(jsonStr);
  55. foreach (Programmer p in list)
  56. {
  57. Response.Write(p + "<br>");//前台输出
  58. }
  59. }
  60. }
    得到的Json文本:
  1. [{"Languages":["C#","Java"],"Name":"李志伟","Sex":true},
  2. {"Languages":["C#","C++"],"Name":"Coder2","Sex":false},
  3. {"Languages":["C#","C++","C","Java"],"Name":"Coder3","Sex":true}]
    注意:此种方式Json序列化对象时,除了只能序列化对象的公有成员外,被序列化的对象还必须有无参的构造方法才能被反序列化!System.Web.Extensions.dll只能在Web项目中引用,在控制台和WinFrom项目中无法引用!
(3)使用System.Runtime.Serialization.dll实现
    代码示例:
  1. [DataContract]//必须申明,否则无法序列化
  2. public class Person
  3. {
  4. [DataMember(Name = "姓名")]//必须申明,否则无法序列化
  5. private string Name;
  6. [DataMember(Name = "性别")]//必须申明,否则无法序列化
  7. private bool Sex;
  8. public Person(string name, bool sex)
  9. {
  10. this.Name = name;
  11. this.Sex = sex;
  12. }
  13. public override string ToString()
  14. {
  15. return "姓名:" + this.Name + "\t性别:" + (this.Sex ? "男" : "女");
  16. }
  17. }
  18. [DataContract]
  19. public class Programmer : Person
  20. {
  21. [DataMember(Name = "编程语言")]
  22. private List<string> Languages;
  23. public Programmer(string name, bool sex, List<string> languages)
  24. : base(name, sex)
  25. {
  26. this.Languages = languages;
  27. }
  28. public override string ToString()
  29. {
  30. StringBuilder str = new StringBuilder();
  31. str.Append(base.ToString() + "\t编程语言:");
  32. foreach (string l in this.Languages)
  33. {
  34. str.Append(l + " ");
  35. }
  36. return str.ToString();
  37. }
  38. }
  39. class Program
  40. {
  41. static void Main(string[] args)
  42. {
  43. string filePath = @"D:\users\lizw\桌面\ObjectJson.txt";
  44. List<string> languages = null;
  45. List<Programmer> list = new List<Programmer>();
  46. languages = new List<string>(new string[] { "C#", "Java" });
  47. list.Add(new Programmer("李志伟", true, languages));
  48. languages = new List<string>(new string[] { "C#", "C++" });
  49. list.Add(new Programmer("Coder2", false, languages));
  50. languages = new List<string>(new string[] { "C#", "C++", "C", "Java" });
  51. list.Add(new Programmer("Coder3", true, languages));
  52. //序列化对象
  53. DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<Programmer>));
  54. MemoryStream ms = new MemoryStream();
  55. ser.WriteObject(ms, list);//将对象转换成json存储
  56. string jsonStr = Encoding.UTF8.GetString(ms.ToArray());
  57. File.WriteAllText(filePath, jsonStr);
  58. //反序列化对象
  59. list.Clear();
  60. ms.Position = 0;
  61. list = (List<Programmer>)ser.ReadObject(ms);
  62. foreach (Programmer p in list)
  63. {
  64. Console.WriteLine(p);
  65. }
  66. ms.Dispose();//关闭内存流
  67. Console.WriteLine("OK!");
  68. Console.Read();
  69. }
  70. }
    得到的Json文本:
  1. [{"姓名":"李志伟","性别":true,"编程语言":["C#","Java"]},
  2. {"姓名":"Coder2","性别":false,"编程语言":["C#","C++"]},
  3. {"姓名":"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类进行只进读取(不常用)
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. //Json字符串
  6. string jsonStr = @"
  7. [{‘Languages‘:[‘C#‘,‘Java‘],‘Name‘:‘李志伟‘,‘Sex‘:true},
  8. {‘Languages‘:[‘C#‘,‘C++‘],‘Name‘:‘Coder2‘,‘Sex‘:false},
  9. {‘Languages‘:[‘C#‘,‘C++‘,‘C‘,‘Java‘],‘Name‘:‘Coder3‘,‘Sex‘:true}]";
  10. JsonTextReader json = new JsonTextReader(new StringReader(jsonStr));
  11. while (json.Read())
  12. {
  13. Console.WriteLine(json.Value + "--" + json.TokenType + "--" + json.ValueType);
  14. }
  15. Console.WriteLine("OK!");
  16. Console.Read();
  17. }
  18. }
(2)使用JArray、JObject、JToken进行读取(常用)
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. //Json字符串
  6. string jsonStr = @"
  7. [{‘Languages‘:[‘C#‘,‘Java‘],‘Name‘:‘李志伟‘,‘Sex‘:true},
  8. {‘Languages‘:[‘C#‘,‘C++‘],‘Name‘:‘Coder2‘,‘Sex‘:false},
  9. {‘Languages‘:[‘C#‘,‘C++‘,‘C‘,‘Java‘],‘Name‘:‘Coder3‘,‘Sex‘:true}]";
  10. JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr);
  11. foreach (JToken jt in ja)
  12. {
  13. JObject jo = (JObject)jt;
  14. JArray temp = (JArray)jo["Languages"];
  15. foreach (JToken token in temp)
  16. {
  17. Console.Write(token+" ");
  18. }
  19. Console.WriteLine("\t" + jo["Name"] + "\t" + jo["Sex"]);
  20. }
  21. Console.WriteLine("OK!");
  22. Console.Read();
  23. }
  24. }
(3)Json时间字符串的处理
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. DateTime time = DateTime.Now;
  6. //这里使用自定义日期格式
  7. IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
  8. timeConverter.DateTimeFormat = "北京时间:yyyy-MM-dd HH:mm:ss";
  9. //序列化时间
  10. string JsonStr = JsonConvert.SerializeObject(time, timeConverter);
  11. Console.WriteLine(JsonStr);
  12. //反序列化时间
  13. DateTime time2 = JsonConvert.DeserializeObject<DateTime>(JsonStr, timeConverter);
  14. Console.WriteLine(time2);
  15. Console.WriteLine("OK!");
  16. Console.Read();
  17. }
  18. }

4.读取Json字符串的技巧

(1)使用匿名类
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. //Json字符串
  6. string jsonStr = @"{‘Languages‘:[‘C#‘,‘Java‘],‘Name‘:‘李志伟‘,‘Sex‘:true}";
  7. //创建匿名类
  8. var TempClass = new { Languages = new string[0], Name = string.Empty, Sex = false };
  9. //反序列化
  10. var O = JsonConvert.DeserializeAnonymousType(jsonStr, TempClass);
  11. Console.WriteLine(O.Name+"\t"+O.Sex+"\t"+O.Languages[1]);
  12. Console.Read();
  13. }
  14. }
(2)使用索引器
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. //Json字符串
  6. string jsonStr = @"{‘Languages‘:[‘C#‘,‘Java‘],‘Name‘:‘李志伟‘,‘Sex‘:true}";
  7. //反序列化
  8. JObject O = JsonConvert.DeserializeObject(jsonStr) as JObject;
  9. //使用索引器访问
  10. Console.WriteLine(O["Name"] + "\t" + O["Sex"] + "\t" + O["Languages"][1]);
  11. Console.Read();
  12. }
  13. }
-------------------------------------------------------------------------------------------------------------------------------




10.C#操作JSON

标签:

原文地址:http://www.cnblogs.com/LiZhiW/p/4316558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!