.net FrameWork 3.5 内置了对JSON的支持,我们可以直接使用。
一。准备
首先引用:System.ServiceModel.Web.dll ,System.Runtime.Serialization.dll 。
然后在using里
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Json;
二。编写需要序列化的类
- 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; }
- }
- }
定义好要序列化的对象和顺序。
三。JSON帮助类
- using System.IO;
- using System.Runtime.Serialization.Json;
- using System.Text;
- namespace Dockty.Data
- {
- public static class JsonHelper<T>
- {
- static JsonHelper()
- { }
- /// <summary>
- /// 序列化为JSON对象
- /// </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>
- /// JSON对象反序列化
- /// </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);
- }
- }
- }
四。序列化与反序列化
- ArtTags tags = new ArtTags() { ArtID = 1, ID = 1, TagID = 1 };
- //序列化
- string strTags = JsonHelper<ArtTags>.WriteObject(tags);
- //反序列化
- ArtTags newTags = JsonHelper<ArtTags>.ReadObject(strTags);
此文章由 Dockty 于 2008-12-26 10:55:10 编辑
引用通告:http://www.Dockty.com/Article/2/Trackback.ashx