• JSON 序列化类 南京酷得软件


    using System;
    using System.Net;
    using System.IO;
    using System.Runtime.Serialization.Json;
    using System.Text;
    
    namespace SFiresoft.Util
    {
        /// <summary>
        /// 提供对JSON格式数据的序列化及反序列化操作类
        /// </summary>
        /// <remarks>
        /// 南京酷得软件 sucsy 2011-8-2
        /// </remarks>
        public class JsonSerializer
        {
            #region JSON序列化操作函数
            /// <summary>
            /// 将传入的数据模型对象序列化为Json
            /// </summary>
            /// <param name="item">要序列化为JSON字符串的对象</param>
            /// <returns></returns>
            public static string JsonSerialize<T>(T item)
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, item);
                    StringBuilder sb = new StringBuilder();
                    sb.Append(Encoding.UTF8.GetString(ms.ToArray(), 0, ms.ToArray().Length));
                    return sb.ToString();
                }
            }
            #endregion
    
            #region JSON反序列化操作函数【包含对流数据及字符串数据两种数据类型的反序列化重载】
            /// <summary>
            /// 将传入的Json序列化为指定的数据模型
            /// </summary>
            /// <param name="mystream">传入的Json</param>
            /// <returns></returns>
            public static T JsonDeserialize<T>(Stream mystream) where T : class
            {
                MemoryStream memoryStream = new MemoryStream();
                int bytes = 1;
                byte[] temp = new byte[4096];
                while (bytes > 0)
                {
                    bytes = mystream.Read(temp, 0, temp.Length);
                    memoryStream.Write(temp, 0, bytes);
                }
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                memoryStream.Position = 0;
                return (T)ser.ReadObject(memoryStream);
            }
    
            /// <summary>
            /// 将Json字符串转换为对象
            /// </summary>
            /// <param name="jsonString">JSON字符串</param>
            /// <returns></returns>
            public static T JsonDeserialize<T>(string jsonString) where T : class
            {
                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                return (T)ser.ReadObject(ms);
            }
            #endregion
        }
    }

    南京酷得软件

    公司网站: http://www.codersoft.cn 专业开发: 气象软件、监狱网上购物系统、两法衔接平台
  • 相关阅读:
    Recommender Systems 基于知识的推荐
    粒子群优化算法简介
    彻底弄懂LSH之simHash算法
    c++ 字符串函数用法举例
    Linux上的运行的jar包
    推荐系统判定标准
    python 细枝末节
    PV UV
    python解析json
    生成n对括号的所有合法排列
  • 原文地址:https://www.cnblogs.com/sucsy/p/3099221.html
Copyright © 2020-2023  润新知