C#中使用JSON不需要使用第三方庫,使用.NET Framwork3.5內建的System.Runtime.Serialization.Json即可很好的完成JSON的解析。
關於JSON的入門介紹見(首頁的圖很形象):
http://www.json.org/
一、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:
JSON Object[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; }
}三、對象轉化為JSON字串
使用WriteObject方法:
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);四、JSON字串轉對象
使用ReadObject方法:
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); 五、輸出結果: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