標籤:
/// <summary> /// 對象轉換成json /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jsonObject">需要格式化的對象</param> /// <returns>Json字串</returns> public static string DataContractJsonSerialize<T>(T jsonObject) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); string json = null; using (MemoryStream ms = new MemoryStream()) //定義一個stream用來存發序列化之後的內容 { serializer.WriteObject(ms, jsonObject); json = Encoding.UTF8.GetString(ms.GetBuffer()); //將stream讀取成一個字串形式的資料,並且返回 ms.Close(); } return json; } /// <summary> /// json字串轉換成對象 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="json">要轉換成對象的json字串</param> /// <returns></returns> public static T DataContractJsonDeserialize<T>(string json) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); T obj = default(T); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { obj = (T)serializer.ReadObject(ms); ms.Close(); } return obj; }
c#json字串和對象的相互轉換