C# Json serialization and deserialization one

黄舟
Release: 2017-02-16 11:01:31
Original
1322 people have browsed it

 public class JsonSerializer
    {
        /// <summary>
        /// json序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string JsonStringSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, t);
                string json = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return json;
            }

        }
        /// <summary>
        /// json反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T DeJsonSerializer<T>(string json)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
               object obj=ser.ReadObject(ms);
               ms.Close();
               if (obj == null)
               {
                   throw new NotImplementedException("序列化实体为NULL,json:" + json);
               }
               return (T)obj;

            }
        }
    }
Copy after login

Josn serialization and deserialization demo

C# Json serialization and deserialization two

The above is the content of C# Json serialization and deserialization one, For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!