asp.net使用DataContractJsonSerializer將對象解析為JSON

來源:互聯網
上載者:User

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}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.