我的问题是,我希望返回camelcases(而不是标准PascalCase) JSON数据通过ActionResults从ASP。NET MVC控制器方法,由JSON.NET序列化。

作为一个例子,考虑下面的c#类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

默认情况下,当从MVC控制器返回这个类的实例作为JSON时,它将以以下方式序列化:

{
  "FirstName": "Joe",
  "LastName": "Public"
}

我希望它被序列化(由JSON.NET)为:

{
  "firstName": "Joe",
  "lastName": "Public"
}

我怎么做呢?


当前回答

将Json NamingStrategy属性添加到类定义中。

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] 公共阶层人 { public string FirstName {get;设置;} 公共字符串LastName {get;设置;} }

其他回答

自定义过滤器的另一种选择是创建一个扩展方法,将任何对象序列化为JSON。

public static class ObjectExtensions
{
    /// <summary>Serializes the object to a JSON string.</summary>
    /// <returns>A JSON string representation of the object.</returns>
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new List<JsonConverter> { new StringEnumConverter() }
        };

        return JsonConvert.SerializeObject(value, settings);
    }
}

然后在从控制器动作返回时调用它。

return Content(person.ToJson(), "application/json");

我是这样做的:

public static class JsonExtension
{
    public static string ToJson(this object value)
    {
        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            NullValueHandling = NullValueHandling.Ignore,
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize
        };
        return JsonConvert.SerializeObject(value, settings);
    }
}

这是MVC核心中一个简单的扩展方法,它会给你项目中的每个对象ToJson()能力,在我看来,在一个MVC项目中,大多数对象应该有成为json的能力,当然这取决于:)

您必须在“Startup.cs”文件中设置设置

您还必须在JsonConvert的默认值中定义它,这是如果您以后想直接使用库来序列化对象。

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options => {
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });
        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
    }

我想这就是你想要的简单答案。这是Shawn Wildermuth的博客:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });

对于WebAPI,请查看这个链接: http://odetocode.com/blogs/scott/archive/2013/03/25/asp-net-webapi-tip-3-camelcasing-json.aspx

基本上,添加以下代码到你的Application_Start:

var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();