关于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;
        }
    }

 

posted @ 2015-02-02 11:07  Serviceboy  阅读(736)  评论(0编辑  收藏  举报