C#中使用JSON不需要使用第三方库,使用.NET Framwork3.5自带的System.Runtime.Serialization.Json即可很好的完成JSON的解析。
关于JSON的入门介绍见(首页的图很形象):
一、Using
需要添加引用:System.ServiceModel.Web 和 System.Runtime.Serialization,然后使用Using:
using System.Runtime.Serialization.Json; using System.Runtime.Serialization;
二、定义序列化的类
假如我们要转化的JSON字符串格式为:
{ "encoding":"UTF-8", "plug-ins":["python","c++","ruby"], "indent": { "length":3, "use_space":true } }
然后编写相应的序列化的类,注意下面类加的Attribute:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
JSON Object[DataContract(Namespace ="http://coderzh.cnblogs.com")] class Config { [DataMember(Order =0)] publicstring encoding { get; set; } [DataMember(Order =1)] publicstring[] plugins { get; set; } [DataMember(Order =2)] public Indent indent { get; set; } } [DataContract(Namespace ="http://coderzh.cnblogs.com")] class Indent { [DataMember(Order =0)] publicint length { get; set; } [DataMember(Order =1)] publicbool use_space { get; set; } }
三、对象转化为JSON字符串
使用WriteObject方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
WriteObject var config =new Config(){ encoding ="UTF-8", plugins =newstring[]{"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 =newbyte[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);
四、JSON字符串转对象
使用ReadObject方法:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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);
五、输出结果:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
JSON stringis: {"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