zoukankan      html  css  js  c++  java
  • 关于Stream的Read方法

    一次做到一个关于使用DataContractJsonSerializer类的表述。其中需要用到MemoryStream数组读取。发生数组溢出错误,这里特记录一笔:

    public static class JsonSerializer<T> where T:new()
        {
            public static string Serialize(T obj)
            {
                string json = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    try
                    {
                        DataContractJsonSerializer jsonS = new DataContractJsonSerializer(typeof(T));
                        jsonS.WriteObject(ms, obj);
                        ms.Position = 0;
                        // 总的要读入的字节数数组
                        byte[] bytes = new byte[ms.Length];
                        // 读取数据的起始点
                        int offset = 0;
    
                        // 判断起始点+偏移量的数据必须在数组总的范围内
                        while (offset+10<ms.Length)
                        {
                            // 尝试读取后10个数据
                            ms.Read(bytes, offset, 10);
                            // 起始点+10
                            offset += 10;
                        }
    
                        //剩余的数组全部读完
                        if (offset + 10 >= ms.Length)
                        {
                            ms.Read(bytes, offset, (int)(ms.Length - offset));
                        }
    
                        json = Encoding.UTF8.GetString(bytes);
                    }
                    catch (Exception ex)
                    {
    
                    }
                }
                return json;
            }
    
            public static T Deserialize(string json)
            {
                T returnValue = default(T);
    
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
                {
                    ms.Position = 0;
                    DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
                    returnValue = (T)ds.ReadObject(ms);
                }
                return returnValue;
            }
        }
  • 相关阅读:
    win10开机时内存使用率达到99%以上
    https的基本原理,看完你的程序员女朋友再也不和你提分手了
    Tomcat样例安全漏洞
    Linux5355端口被0.0.0.0监听
    jQuery的ajax
    事件委托(事件代理)
    jQuery的事件绑定和解绑
    事件对象
    JS的事件流的概念(重点)
    jQuery的位置信息
  • 原文地址:https://www.cnblogs.com/ServiceboyNew/p/4267236.html
Copyright © 2011-2022 走看看