破人

导航

Json序列化与反序列化

http://www.cnblogs.com/dlonghow/archive/2009/02/19/1393702.html

//空接口
public interface IJson
{
}
public static class JsonHelper
{
public static string ToJson(this IJson source)
    {
return ToJson(source, source.GetType());
    }
public static string ToJson(this IJson source, Type type)
    {
        DataContractJsonSerializer serilializer = new DataContractJsonSerializer(type);
using (Stream stream = new MemoryStream())
        {
            serilializer.WriteObject(stream, source);
            stream.Flush();
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
        }
    }
public static T ParseJSON<T>(this string str)
    {
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str)))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
        }
    }
// 通过JSON序列化深度克隆类型
public static T DeepClone<T>(this IJson Source) where T : IJson
    {
string jsonString = Source.ToJson();
return jsonString.ParseJSON<T>();
    }
}

posted on 2010-03-07 14:14  破人  阅读(179)  评论(0编辑  收藏  举报