C#技术百科
问问你的心你有没有信心 做事情要专一坚定,执着

    public class JSONConverter<T>
    {
        public static string toJson(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, obj);

            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            string dataString = Encoding.UTF8.GetString(dataBytes);
            stream.Close();


            return dataString;
        }

        public static T toObject(string str)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

            MemoryStream mStream = new MemoryStream(Encoding.Default.GetBytes(str));
            T obj = (T)serializer.ReadObject(mStream);
            mStream.Close();

            return obj;
        }
    }

posted on 2011-07-29 17:04  王德田  阅读(1434)  评论(0编辑  收藏  举报