from:http://www.dockty.com/Article/aspnet_json_net30.aspx
.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);
欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!
本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2009/07/20/1527169.html
,如需转载请自行联系原作者