. NET Framework 3.5 has built-in support for JSON, which can be directly used.
I. Preparation
First, reference: system. servicemodel. Web. dll, system. runtime. serialization. dll.
Then in using
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Json;
II. Compile the classes to be serialized
- using System.Runtime.Serialization;
- namespace Dockty.Data
- {
- [DataContract(Namespace = "http://www.dockty.com")]
- public class ArtTags
- {
- public ArtTags() { }
- [DataMember(Order = 0)]
- public int ID { get; set; }
- [DataMember(Order = 1)]
- public int TagID { get; set; }
- [DataMember(Order = 2)]
- public int ArtID { get; set; }
- }
- }
Define the object and sequence to be serialized.
3. JSON help class
- Using system. IO;
- Using system. runtime. serialization. JSON;
- Using system. text;
-
- Namespace dockty. Data
- {
- Public static class jsonhelper <t>
- {
- Static jsonhelper ()
- {}
-
- /// <Summary>
- /// Serialized as a JSON object
- /// </Summary>
- /// <Param name = "OBJ"> </param>
- /// <Returns> </returns>
- Public static string writeobject (t obj)
- {
- VaR serializer = new datacontractjsonserializer (typeof (t ));
- VaR mstream = new memorystream ();
- Serializer. writeobject (mstream, OBJ );
- Byte [] bytes = new byte [mstream. Length];
- Mstream. Position = 0;
- Mstream. Read (bytes, 0, (INT) mstream. Length );
- Return encoding. utf8.getstring (bytes );
- }
-
- /// <Summary>
- /// Deserialization of JSON objects
- /// </Summary>
- /// <Param name = "data"> </param>
- /// <Returns> </returns>
- Public static t readobject (string data)
- {
- VaR mstream = new memorystream (encoding. utf8.getbytes (data ));
- VaR serializer = new datacontractjsonserializer (typeof (t ));
- Return (t) serializer. readobject (mstream );
- }
- }
- }
4. Serialization and deserialization
- Arttags tags = new arttags () {artid = 1, id = 1, tagid = 1 };
- // Serialization
- String strtags = jsonhelper <arttags>. writeobject (TAGS );
- // Deserialization
- Arttags newtags = jsonhelper <arttags>. readobject (strtags );
This article was edited by dockty at 10:55:10:
. Net 3.5, ASP. NET, JSON, C #
Reference announcement: Notice