C# JSON協助類(可互轉)

來源:互聯網
上載者:User

標籤:style   blog   io   color   ar   sp   for   div   on   

 public class JsonHelper    {        public JsonHelper()        {            //            // TODO: Add constructor logic here            //        }        /// <summary>        /// 把對象序列化 JSON 字串         /// </summary>        /// <typeparam name="T">物件類型</typeparam>        /// <param name="obj">對象實體</param>        /// <returns>JSON字串</returns>        public static string GetJson<T>(T obj)        {            //記住 添加引用 System.ServiceModel.Web             /**             * 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不來的哦             * */            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));            using (MemoryStream ms = new MemoryStream())            {                json.WriteObject(ms, obj);                string szJson = Encoding.UTF8.GetString(ms.ToArray());                return szJson;            }        }        /// <summary>        /// 把JSON字串還原為對象        /// </summary>        /// <typeparam name="T">物件類型</typeparam>        /// <param name="szJson">JSON字串</param>        /// <returns>對象實體</returns>        public static T ParseFormJson<T>(string szJson)        {            T obj = Activator.CreateInstance<T>();            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))            {                DataContractJsonSerializer dcj = new DataContractJsonSerializer(typeof(T));                return (T)dcj.ReadObject(ms);            }        }    }
//因為在webservice中是不能接收集合的 所以用字串接收選擇了json.//調用:List<BIZ.T_ExEntryDetailModel> ExdetailModel ExdetailModel = UPED.JsonHelper.ParseFormJson<List<BIZ.T_ExEntryDetailModel>>(jsonStr);   //解析JSON串為類  //實體類轉換JSON串為類List<Models.ExEntryDetailModel> detailModel =servers.GetExEntryDetailModel(......);string jsonStr = UPED.JsonHelper.GetJson<List<Models.ExEntryDetailModel>>(detailModel);

 

C# JSON協助類(可互轉)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.