我的问题是,我希望返回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。
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");
或者,简单地说:
JsonConvert.SerializeObject(
<YOUR OBJECT>,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
例如:
return new ContentResult
{
ContentType = "application/json",
Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }),
ContentEncoding = Encoding.UTF8
};