JSON, JavaScript Object Notation, is a lighter and more friendly format for interface (Ajax, rest, etc.) data exchange. As a substitute for XML, it is used to represent the format of data exchange between the client and the server.
Third-party libraries are not required to use JSON in C #. You can use the system. runtime. serialization. JSON file that comes with. Net framwork3.5 to parse JSON. It uses the. NET serialization mechanism to serialize objects into JSON strings and return them to the client for resolution.
First, define a class:
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}
Then, use the serialization method to serialize the class to JSON:
Code
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 ();
The generated JSON object is:
{"Blockid": 1, "blockname": "name", "maplng": 0, "maplat": 0, "listorder": 1, "areaid": 0}