webapi转化为json格式

引用命名空间:

using System.Web.Script.Serialization;
using System.Text;

(using system.web.Mvc;)

添加引用:

Newtonsoft.json

system.web.Entity

system.web.Extensions

 

 

Controller:

        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;
        }

 


        public HttpResponseMessage get()
        {

            var jg = db.user.ToList();
            return toJson(jg);

        }

posted @ 2017-04-22 10:32  suan1717  阅读(709)  评论(0编辑  收藏  举报