asp.net使用DataContractJsonSerializer将对象解析为JSON

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}

原文地址:https://www.cnblogs.com/hyl8218/p/1643848.html