C#有两种常见办法可以解析和使用JSON:一是使用.NET Framwork3.5或更高版本自带的System.Runtime.Serialization.Json库。二是使用Newtonsoft提供的JSON解析库。下面分别介绍。
一、使用系统自带库
1、Using
首先,需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
- using System.Runtime.Serialization.Json;
- using System.Runtime.Serialization;
2、定义序列化的类
假如我们要转化的JSON字符串格式为:
- {
- "encoding":"UTF-8",
- "plug-ins":["python","c++","ruby"],
- "indent":{
- "length":3,
- "use_space":true
- }
- }
然后编写相应的序列化的类,注意下面类加的Attribute:
- [DataContract(Namespace = "http://coderzh.cnblogs.com")]
- class Config
- {
- [DataMember(Order = 0)]
- public string encoding { get; set; }
- [DataMember(Order = 1)]
- public string[] plugins { get; set; }
- [DataMember(Order = 2)]
- public Indent indent { get; set; }
- }
- [DataContract(Namespace = "http://coderzh.cnblogs.com")]
- class Indent
- {
- [DataMember(Order = 0)]
- public int length { get; set; }
- [DataMember(Order = 1)]
- public bool use_space { get; set; }
- }
3、对象转化为JSON字符串
使用WriteObject方法:
- var config = new Config(){
- encoding = "UTF-8",
- plugins = new string[]{"python", "C++", "C#"},
- indent = new Indent(){ length = 4, use_space = false}
- };
- var serializer = new DataContractJsonSerializer(typeof(Config));
- var stream = new MemoryStream();
- serializer.WriteObject(stream, config);
- byte[] dataBytes = new byte[stream.Length];
- stream.Position = 0;
- stream.Read(dataBytes, 0, (int)stream.Length);
- string dataString = Encoding.UTF8.GetString(dataBytes);
- Console.WriteLine("JSON string is:");
- Console.WriteLine(dataString);
4、JSON字符串转对象
使用ReadObject方法:
- var mStream = new MemoryStream(Encoding.Default.GetBytes(dataString));
- Config readConfig = (Config)serializer.ReadObject(mStream);
- Console.WriteLine("Encoding is: {0}", readConfig.encoding);
- foreach (string plugin in readConfig.plugins)
- {
- Console.WriteLine("plugins is: {0}", plugin);
- }
- Console.WriteLine("indent.length is: {0}", readConfig.indent.length);
- Console.WriteLine("indent.use_space is: {0}", readConfig.indent.use_space);
5、输出结果:
- JSON string is:
- {"encoding":"UTF-8","plugins":["python","C++","C#"],"indent":{"length":4,"use_space":false}}
- Encoding is: UTF-8
- plugins is: python
- plugins is: C++
- plugins is: C#
- indent.length is: 4
- indent.use_space is: False
二、Newtonsoft提供的Json.dll
这是一个Newtonsoft提供的第三方库,需要下载并引用dll:Newtonsoft.Json.dll。官方下载地址: http://www.newtonsoft.com/
使用示例如下:
- //读取简单的json
- string json="{\"username\":\"张三\"}";
- string username = string.Empty;
- JObject jObj=JObject.Parse(json); //进行格式化
- username = jObj["username"].ToString();
- Console.WriteLine(username);
- //读取嵌套对象的json
- json = "{\"username\":\"张三\",data:{\"address\":\"福建厦门\"}}";
- jObj = JObject.Parse(json);
- string address = string.Empty;
- address = jObj["data"]["address"].ToString();
- Console.WriteLine(address);
- //读取数组,操作方式与数组类似
- json = "{\"username\":\"张三\",data:[{\"address\":\"福建厦门\"},{\"address\":\"福建福州\"}]}";
- jObj = JObject.Parse(json);
- address = string.Empty;
- address = jObj["data"][0]["address"].ToString()+","+ jObj["data"][1]["address"].ToString();
- Console.WriteLine(address);
- Console.ReadLine();
转载本站内容时,请务必注明来自W3xue,违者必究。