将对象序列化成json



 public static class JsonFormatter
    {
        /// <summary>
        /// 将对象序列化json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Serialize<T>(T value)
        {
            if (value == nullreturn null;
            using (var ms = new MemoryStream())
            {   
                var ser = new DataContractJsonSerializer(typeof(T));
                ser.WriteObject(ms, value);
                ms.Position = 0;
                using(var sr = new StreamReader(ms, System.Text.Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }
posted @ 2012-08-29 14:04  If_1989  阅读(238)  评论(0编辑  收藏  举报