从Web API返回camelCased JSON

前端之家收集整理的这篇文章主要介绍了从Web API返回camelCased JSON前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图从ASP.Net Web API 2控制器返回骆驼包装的 JSON.我创建了一个新的Web应用程序,其中只有ASP.Net MVC和Web API位.我像这样劫持了ValueController:
public class ValuesController : ApiController
{
    public class Thing
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }

        public string[] Tags { get; set; }
    }

    // GET api/values
    public IHttpActionResult Get()
    {
        var thing = new Thing
        {
            Id = 123,FirstName = "Brian",ISBN = "ABC213",ReleaseDate = DateTime.Now,Tags = new string[] { "A","B","C","D"}
        };

        return Json(thing);
    }
}

在IE中运行,我得到以下结果:

{"Id":123,"FirstName":"Brian","ISBN":"ABC213","ReleaseDate":"2014-10-20T16:26:33.6810554-04:00","Tags":["A","D"]}

关于这个主题K. Scott Allen’s post以后,我将以下内容添加到WebApiConfig.cs文件中的Register方法中:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var formatters = GlobalConfiguration.Configuration.Formatters;
        var jsonFormatter = formatters.JsonFormatter;
        var settings = jsonFormatter.SerializerSettings;
        settings.Formatting = Formatting.Indented;
        settings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
        );
    }

但是,我仍然得到同样的结果,在我的结果.有没有我失踪的东西?我尝试了其他一些方法,但没有任何工作.

解决方法

在您的WebApiConfig.cs中,请确保添加这两行
// Serialize with camelCase formatter for JSON.
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

确保您安装了Newtonsoft库.

希望有帮助.

猜你在找的HTML相关文章