您可以为此创建一个自定义合同解析器。以下合同解析器会将所有密钥转换为小写:
public class LowercaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
用法:
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.SerializeObject(authority, Formatting.Indented, settings);
威尔导致:
{"username":"Mark","apitoken":"xyzABC1234"}
如果您始终想使用进行序列化LowercaseContractResolver
,请考虑将其包装在一个类中,以避免重复自己的操作:
public class LowercaseJsonSerializer
{
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
ContractResolver = new LowercaseContractResolver()
};
public static string SerializeObject(object o)
{
return JsonConvert.SerializeObject(o, Formatting.Indented, Settings);
}
public class LowercaseContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return propertyName.ToLower();
}
}
}
可以这样使用:
var json = LowercaseJsonSerializer.SerializeObject(new { Foo = "bar" });
// { "foo": "bar" }
ASP.NET MVC4 / WebAPI
如果您使用的是ASP.NET MVC4 / WebAPI,则可以使用CamelCasePropertyNamesContractResolver
Newtonsoft.Json库,该库默认包含。