JSON,JavaScript Object Notation,是一種更輕、更友好的用於介面(AJAX、REST等)資料交換的格式。作為XML的一種替代品,用於表示用戶端與伺服器間資料交換承載的格式。
在C#中使用JSON不需要使用第三方庫,使用.NET Framwork3.5內建的System.Runtime.Serialization.Json即可很好的完成JSON的解析。它使用.Net的序列化機制,將對象序列化為Json的字串,返回給用戶端解析。
首先定義一個類:
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
1 [DataContract(Namespace="http://hyl8218.cnblogs.com")]
2 public class Block
3 {
4 private byte _blockId = 1;
5 [DataMember(Order = 0)]
6 public byte BlockId
7 {
8 set { _blockId = value; }
9 get { return _blockId; }
10 }
11
12 private int _areaId = 0;
13 [DataMember(Order = 5)]
14 public int AreaId
15 {
16 set { _areaId = value; }
17 get { return _areaId; }
18 }
19
20 private string _blockName = "Name";
21 [DataMember(Order = 1)]
22 public string BlockName
23 {
24 set { _blockName = value; }
25 get { return _blockName.Truncate(8); }
26 }
27
28 private int _listOrder = 1;
29 [DataMember(Order = 4)]
30 public int ListOrder
31 {
32 set { _listOrder = value; }
33 get { return _listOrder; }
34 }
35
36 private decimal _mapLng = 0;
37 [DataMember(Order = 2)]
38 public decimal MapLng
39 {
40 set { _mapLng = value; }
41 get { return _mapLng; }
42 }
43
44 private decimal _mapLat = 0;
45 [DataMember(Order = 3)]
46 public decimal MapLat
47 {
48 set { _mapLat = value; }
49 get { return _mapLat; }
50 }
51 }
然後使用序列化方法將類序列化為Json:
代碼
Block block = new Block();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Block));
MemoryStream stram = new MemoryStream();
serializer.WriteObject(stram, block);
byte[] data = new byte[stram.Length];
stram.Position = 0;
stram.Read(data, 0, (int)stram.Length);
string jsonString = Encoding.UTF8.GetString(data);
Response.Write(jsonString);
Response.End();
產生的Json對象為:
{"BlockId":1,"BlockName":"Name","MapLng":0,"MapLat":0,"ListOrder":1,"AreaId":0}