通用的返回json的数据格式,简单实用

 

    public class JsonResultHelper
    {
        /// <summary>
        /// 成功返回json时调用,格式:带有状态码 1,和序列化后数据
        /// 如果字段有时间格式,默认显示到day
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static HttpResponseMessage GetJsonWithResultAndInfo(object data)
        {
            var resultStr = JsonConvert.SerializeObject(
                new { ret = 1, body = data },
                new JsonSerializerSettings()
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver(),
                    DateFormatString = "yyyy-MM-dd"
                });

            HttpResponseMessage responseMsg = new HttpResponseMessage
            {
                Content = new StringContent(resultStr, Encoding.GetEncoding("UTF-8"), "application/json")
            };

            return responseMsg;
        }

        /// <summary>
        /// 只返回状态码和提示信息,成功失败时都可以调用
        /// </summary>
        /// <param name="ret"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static HttpResponseMessage GetJsonWithInfo(int ret, string msg)
        {
            var resultStr = JsonConvert.SerializeObject(new { ret = ret, msg = msg });

            HttpResponseMessage responseMsg = new HttpResponseMessage
            {
                Content = new StringContent(resultStr, Encoding.GetEncoding("UTF-8"), "application/json")
            };

            return responseMsg;
        }

        /// <summary>
        /// 只返回序列化后结果,成功失败时都可以调用
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static HttpResponseMessage GetJsonWithResult(object data)
        {
            var resultStr = JsonConvert.SerializeObject(data);

            HttpResponseMessage responseMsg = new HttpResponseMessage
            {
                Content = new StringContent(resultStr, Encoding.GetEncoding("UTF-8"), "application/json")
            };

            return responseMsg;
        }

    }

 

posted on 2018-02-23 10:30  奔游浪子  阅读(905)  评论(0)    收藏  举报

导航