.Net 2.0自带的Json序列化、反序列化方法

public class JsonUtil
    {
        public static T DeserializeObject<T>(string json)
        {
            DataContractJsonSerializer jsonFormator = new DataContractJsonSerializer(typeof(T));
            using (Stream readStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                return (T)jsonFormator.ReadObject(readStream);
            }
        }

        public static string SerializeObject(object obj)
        {
            DataContractJsonSerializer jsonFormator = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream stream = new MemoryStream())
            {
                jsonFormator.WriteObject(stream, obj);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }
    }

posted on 2015-10-21 14:45  东篱南山  阅读(1434)  评论(1编辑  收藏  举报

导航