本文介绍了在类级别配置Json.NET序列化设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用驼峰式命名约定对我的类进行序列化和反序列化.我知道我可以按照此处所述使用JsonConvert.SerializeObject(object, settings)重载:

I want my class to be serialized and deserialized using camel case naming convention. I know I can use the JsonConvert.SerializeObject(object, settings) overload as stated here:

var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(product, serializerSettings);

有没有办法在类级别(通过属性)应用相同的配置,这样我就不必覆盖序列化设置?

Is there any way to apply the same configuration on a class level (via attributes) so that I do not need to override the serialization settings?

我可以写一个自定义转换器,但是看起来像对这样简单的事情的过度杀伤.

I could write a custom converter but that looks like an overkill for such a simple thing.

推荐答案

如果使用的是Json.NET 9.0.1或更高版本,则可以使用JsonObjectAttribute上的NamingStrategyType属性来实现所需的功能.如果需要将参数传递给NamingStrategy的构造函数,请使用NamingStrategyParameters属性指定它们.下面是一个如何使用驼峰案例命名策略指定类的示例.

If you're using Json.NET 9.0.1 or later you can use the NamingStrategyType property on the JsonObjectAttribute to achieve what you want. If you need to pass arguments to the NamingStrategy's constructor then specify them with the NamingStrategyParameters property. Below is an example of how to specify a class with a camel case naming strategy.

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class Foo
{
    public string Bar;
}

这篇关于在类级别配置Json.NET序列化设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:20