一個簡單的Json轉換器

暖楓無敵發表於2011-12-09
public class JsonConverter
	{
		public static Encoding Encoding = Encoding.UTF8;

		public static T GetObject<T>(string json)
		{
			return (T)GetObject(typeof(T), json);
		}

		public static T GetObject<T>(Stream stream)
		{
			return (T)GetObject(typeof(T), stream);
		}

		public static object GetObject(Type type, string json)
		{
			using (MemoryStream ms = new MemoryStream(Encoding.GetBytes(json)))
			{
				return GetObject(type, ms);
			}
		}

		public static object GetObject(Type type, Stream stream)
		{
			DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
			return serializer.ReadObject(stream);
		}
	}

     [DataContract]
    public class Error
    {
        [DataMember(Name = "status")]
        public string Status { get; set; }

        [DataMember(Name = "reason")]
        public string Reason { get; set; }
    }



相關文章