我正在使用http://json.codeplex.com/,我正在谈论基于Ruby的Rest API。问题是大多数属性都有一个ruby下划线命名约定。我想知道是否有人知道一种方法,以便我可以避免添加大量的JsonProperty。
例如,我想避免添加JsonProperty属性并在序列化程序设置中内置一个约定,以便它知道在.NET命名约定中尝试使用下划线映射属性:)
public class Member
{
[JsonProperty(PropertyName = "avatar_url")]
public string AvatarUrl { get; set; }
[JsonProperty(PropertyName = "twitter_screen_name")]
public string TwitterScreenName { get; set; }
[JsonProperty(PropertyName = "website_url")]
public string WebSiteUrl { get; set; }
}
答案 0 :(得分:33)
更新 - 2016年9月:
Json.NET 9.0.1有 SnakeCaseNamingStrategy 。您可以使用它自动获得twitter_screen_name样式属性。
继承DefaultContractResolver
并覆盖ResolvePropertyName
以格式化您想要的属性名称。
CamelCasePropertyNamesContractResolver
对属性名称进行了类似的全局更改。
答案 1 :(得分:30)
阅读本文:http://nyqui.st/json-net-newtonsoft-json-lowercase-keys
public class UnderscoreMappingResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
return System.Text.RegularExpressions.Regex.Replace(
propertyName, @"([A-Z])([A-Z][a-z])|([a-z0-9])([A-Z])", "$1$3_$2$4").ToLower();
}
}
答案 2 :(得分:10)
从版本9开始,存在一个新的命名策略属性,它有一个内置的SnakeCaseNamingStrategy类。使用以下代码并将contractResolver
注册为SerializerSettings.ContractResolver
。
var contractResolver = new DefaultContractResolver();
contractResolver.NamingStrategy = new SnakeCaseNamingStrategy();
默认情况下,该类不包含字典,并且它不会覆盖任何手动设置的属性值。这些是可以在重载中传递的两个参数:
// true parameter forces handling of dictionaries
// false prevents the serializer from changing anything manually set by an attribute
contractResolver.NamingStrategy = new SnakeCaseNamingStrategy(true, false);
答案 3 :(得分:4)
var settings = new JsonSerializerSettings
{
ContractResolver = new PascalCaseToUnderscoreContractResolver()
};
var rawJson = "{ test_property:'test' }"
var myObject = JsonConvert.DeserializeObject<MyObjectType>(rawJson, settings);
https://www.nuget.org/packages/Humanizer/1.37.7
http://humanizr.net/#underscore
public class PascalCaseToUnderscoreContractResolver : DefaultContractResolver
{
protected override string ResolvePropertyName(string propertyName) => propertyName.Underscore();
}
public Class MyObjectType
{
public string TestProperty {get;set;}
}