JSON转换

View Code
public static T Json2Obj<T>(string json)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                return (T)serializer.ReadObject(ms);
            }
        }

        public static string Obj2Json<T>(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, obj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }

需要引用System.Runtime.Serialization和System.ServiceModel.Web

posted @ 2013-04-11 16:58  stone87654321  阅读(123)  评论(0编辑  收藏  举报