c#,Model 实体转json,字符串转json

  public class JsonF
    {
        #region 字符串转json
        /// <summary>
        /// 字符串转json
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static HttpResponseMessage toJson(Object obj)
        {
            String str;
            if (obj is String || obj is Char)
            {
                str = obj.ToString();
            }
            else
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                str = serializer.Serialize(obj);
            }
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion

        #region Model 实体转json
        /// <summary>
        /// Model 实体转json
        /// </summary>
        /// <param name="Model">可以是单个实体,也可是实体集(即:ToList())</param>
        /// <returns></returns>
        public static HttpResponseMessage PostModel(object Model)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string str = serializer.Serialize(Model);
            HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }
        #endregion
    }

 

posted @ 2018-05-08 10:01  紫晶城  阅读(3644)  评论(0编辑  收藏  举报