.net4.0 实体与json相互转换

using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;

//http://blog.csdn.net/lee576/archive/2009/01/08/3736880.aspx

namespace Zhuyi.Utility
{

    public static class JsonUtility
    {
        public static string ObjectToJson(object item)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, item);
                StringBuilder sb = new StringBuilder();
                sb.Append(Encoding.UTF8.GetString(ms.ToArray()));
                return sb.ToString();
            }
        }

        public static T JsonToObject<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T jsonObject = (T)ser.ReadObject(ms);
            ms.Close();
            return jsonObject;
        }
    }
}

你可能感兴趣的:(.net4.0 实体与json相互转换)