我们有一个Json.NET设置程序,它将合同解析器设置为CamelCasePropertyNamesContractResolver。但是,对于某些类型,我想选择退出camelCasing行为。是否有可能通过某种方式注释这些类型?如何退出JSON合约解析器
3
A
回答
3
是的,截至Json.Net version 9.0.1(2016年6月),[JsonObject]
和[JsonProperty]
属性均支持NamingStrategyType
参数。因此,您可以使用CamelCasePropertyNamesContractResolver
来设置默认的命名方案,但选择退出或甚至将这些属性更改为使用特定类或属性的不同策略。
这里是一个简短的演示:
public class Program
{
public static void Main(string[] args)
{
Foo foo = new Foo
{
CamelCasedProperty = "abc def",
AlsoCamelCasedButChildPropsAreNot = new Bar
{
SomeProperty = "fizz buzz",
AnotherProperty = "whiz bang"
},
ThisOneOptsOutOfCamelCasing = "blah blah",
ThisOneIsSnakeCased = "senssssational"
};
var settings = new JsonSerializerSettings
{
// set up default naming scheme
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
}
}
class Foo
{
public string CamelCasedProperty { get; set; }
public Bar AlsoCamelCasedButChildPropsAreNot { get; set; }
[JsonProperty(NamingStrategyType = typeof(DefaultNamingStrategy))]
public string ThisOneOptsOutOfCamelCasing { get; set; }
[JsonProperty(NamingStrategyType = typeof(SnakeCaseNamingStrategy))]
public string ThisOneIsSnakeCased { get; set; }
}
[JsonObject(NamingStrategyType = typeof(DefaultNamingStrategy))]
class Bar
{
public string SomeProperty { get; set; }
public string AnotherProperty { get; set; }
}
输出:
{
"camelCasedProperty": "abc def",
"alsoCamelCasedButChildPropsAreNot": {
"SomeProperty": "fizz buzz",
"AnotherProperty": "whiz bang"
},
"ThisOneOptsOutOfCamelCasing": "blah blah",
"this_one_is_snake_cased": "senssssational"
}
小提琴:
+0
如果我没有访问类Bar(因为它来自第三方),但我实际上是想强制AlsoCamelCasedButChildPropsAreNot以使其具有其属性CamelCase?有没有办法通过属性装饰器来做到这一点?请参阅[问题](https://stackoverflow.com/questions/46326475/how-can-i-make-the-properties-of-sub-class-camel-case) – CodeHacker
相关问题
- 1. 如何解析json输出?
- 2. 如何解析JSON输出?
- 3. 使用Blackberry JSON解析器,如何解析出字符串“[”?
- 4. 计划解析“退出”
- 5. 如何解析json?
- 6. 如何解析JSON
- 7. Python-JSON - 如何解析API输出?
- 8. 如何解析JSON文件,而无需使用JSON库和JSON解析器
- 9. JSON解析器输出显示在tableview
- 10. ios json解析子集合
- 11. Complex Json解析器
- 12. JSON解析器-java.lang.NoSuchFieldError:defaultReader
- 13. Kotlin Json解析器
- 14. JSON CSS解析器
- 15. 使用Streaming API和Json解析器进行JSON解析 - 混合模式
- 16. 如何使JSON解析器解析java中的elasticsearch映射?
- 17. 退出UIViewController的问题,而JSON仍然被解析
- 18. 如何解析JSON,如geo:point?
- 19. Haskell JSON解析器不解析对象
- 20. 编辑JSON解析器来解析geoJSON?
- 21. 解析JSON输出在PHP
- 22. 解析JSON值时出错
- 23. 解析JSON时出错
- 24. JSON:解析时出错
- 25. Python Json解析输出
- 26. 解析JSON抛出错误
- 27. 解析JSON失败/列出
- 28. Scrapy解析JSON输出
- 29. Python - 解析(fio)json输出
- 30. Android:解析JSON时出错
您使用的是什么版本的.NET? – Delosdos
是任何用途:http://stackoverflow.com/questions/19956838/force-camelcase-on-asp-net-webapi-per-controller你可以设置每个控制器的解析器。 – Delosdos
@Delosdos这是针对.NET 4.6库的,不适用于特定的Web框架。 – ChaseMedallion