课程表

C# 基础教程

C# 高级教程

C# 工具/手册

工具箱
速查手册

C# 使用 JSON

当前位置:免费教程 » 程序设计 » C#

C#有两种常见办法可以解析和使用JSON:一是使用.NET Framwork3.5或更高版本自带的System.Runtime.Serialization.Json库。二是使用Newtonsoft提供的JSON解析库。下面分别介绍。

一、使用系统自带库

1、Using

首先,需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:

  1. using System.Runtime.Serialization.Json;
  2. using System.Runtime.Serialization;

2、定义序列化的类

假如我们要转化的JSON字符串格式为:

  1. {
  2. "encoding":"UTF-8",
  3. "plug-ins":["python","c++","ruby"],
  4. "indent":{
  5. "length":3,
  6. "use_space":true
  7. }
  8. }

然后编写相应的序列化的类,注意下面类加的Attribute:

  1. [DataContract(Namespace = "http://coderzh.cnblogs.com")]
  2. class Config
  3. {
  4. [DataMember(Order = 0)]
  5. public string encoding { get; set; }
  6. [DataMember(Order = 1)]
  7. public string[] plugins { get; set; }
  8. [DataMember(Order = 2)]
  9. public Indent indent { get; set; }
  10. }
  11.  
  12. [DataContract(Namespace = "http://coderzh.cnblogs.com")]
  13. class Indent
  14. {
  15. [DataMember(Order = 0)]
  16. public int length { get; set; }
  17. [DataMember(Order = 1)]
  18. public bool use_space { get; set; }
  19. }

3、对象转化为JSON字符串

使用WriteObject方法:

  1. var config = new Config(){
  2. encoding = "UTF-8",
  3. plugins = new string[]{"python", "C++", "C#"},
  4. indent = new Indent(){ length = 4, use_space = false}
  5. };
  6. var serializer = new DataContractJsonSerializer(typeof(Config));
  7. var stream = new MemoryStream();
  8. serializer.WriteObject(stream, config);
  9. byte[] dataBytes = new byte[stream.Length];
  10. stream.Position = 0;
  11. stream.Read(dataBytes, 0, (int)stream.Length);
  12. string dataString = Encoding.UTF8.GetString(dataBytes);
  13. Console.WriteLine("JSON string is:");
  14. Console.WriteLine(dataString);

4、JSON字符串转对象

使用ReadObject方法:

  1. var mStream = new MemoryStream(Encoding.Default.GetBytes(dataString));
  2. Config readConfig = (Config)serializer.ReadObject(mStream);
  3.  
  4. Console.WriteLine("Encoding is: {0}", readConfig.encoding);
  5. foreach (string plugin in readConfig.plugins)
  6. {
  7. Console.WriteLine("plugins is: {0}", plugin);
  8. }
  9. Console.WriteLine("indent.length is: {0}", readConfig.indent.length);
  10. Console.WriteLine("indent.use_space is: {0}", readConfig.indent.use_space);

5、输出结果:

  1. JSON string is:
  2. {"encoding":"UTF-8","plugins":["python","C++","C#"],"indent":{"length":4,"use_space":false}}
  3. Encoding is: UTF-8
  4. plugins is: python
  5. plugins is: C++
  6. plugins is: C#
  7. indent.length is: 4
  8. indent.use_space is: False

二、Newtonsoft提供的Json.dll

这是一个Newtonsoft提供的第三方库,需要下载并引用dll:Newtonsoft.Json.dll。官方下载地址: http://www.newtonsoft.com/

使用示例如下:

  1. //读取简单的json
  2. string json="{\"username\":\"张三\"}";
  3. string username = string.Empty;
  4. JObject jObj=JObject.Parse(json); //进行格式化
  5. username = jObj["username"].ToString();
  6. Console.WriteLine(username);
  7.  
  8. //读取嵌套对象的json
  9. json = "{\"username\":\"张三\",data:{\"address\":\"福建厦门\"}}";
  10. jObj = JObject.Parse(json);
  11. string address = string.Empty;
  12. address = jObj["data"]["address"].ToString();
  13. Console.WriteLine(address);
  14.  
  15. //读取数组,操作方式与数组类似
  16. json = "{\"username\":\"张三\",data:[{\"address\":\"福建厦门\"},{\"address\":\"福建福州\"}]}";
  17. jObj = JObject.Parse(json);
  18. address = string.Empty;
  19. address = jObj["data"][0]["address"].ToString()+","+ jObj["data"][1]["address"].ToString();
  20. Console.WriteLine(address);
  21.  
  22. Console.ReadLine();
转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号