C#数据实体与JSON数据的互转

 public readonly static SerializeHelper Instance = new SerializeHelper();

        /// 
        /// 将C#数据实体转化为JSON数据
        /// 
        /// 要转化的数据实体
        /// JSON格式字符串
        public string JsonSerialize(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, obj);
            stream.Position = 0;

            StreamReader sr = new StreamReader(stream);
            string resultStr = sr.ReadToEnd();
            sr.Close();
            stream.Close();

            return resultStr;
        }

        /// 
        /// 将JSON数据转化为C#数据实体
        /// 
        /// 符合JSON格式的字符串
        /// T类型的对象
        public T JsonDeserialize(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json.ToCharArray()));
            T obj = (T)serializer.ReadObject(ms);
            ms.Close();

            return obj;
        }

 

你可能感兴趣的:(C#winfrom)