WebAPI返回JSON的正确格式

时间:2024-01-09 22:01:38

最近打算用WebAPI做服务端接口,返回JSON供ANDROID程序调用,结果试了好几次JSONObject都无法解析返回的JSON字符串。看了一下服务端代码:

       public string Get()
{
return "{\"errNum\":300202,\"errMsg\":\"Missing apikey\"}";
}

打开CHROME浏览器,F12查看了一下返回信息,发现返回头Content-Type是"application/xml; charset=utf-8"类型,原来WebAPI默认是返回XML类型, 有人说可以在Global.asax添加配置,代码如下:

        protected void Application_Start()
{
AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles); // 使api返回为json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}

按照上面方法做了之后,再F12的确是返回“application/json”了,本以为到此就结束了,万万没想到的是JSONObject再次解析异常。之后又尝试了好几种方法,最后通过下面的方法终于返回了可以解析的JSON字符。

       public HttpResponseMessage Get()
{
string json = "{\"errNum\":300202,\"errMsg\":\"Missing apikey\"}";
return new HttpResponseMessage { Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") };
}

总结:其实WebAPI默认建议使用RESTful风格,根据GET\POST\PUT\DELETE调用不同的ACTION,并返回HttpResponseMessage,我们可以很灵活地定义HttpResponseMessage。