在类级别配置 Json.NET 序列化设置 [英] Configure Json.NET serialization settings on a class level

查看:24
本文介绍了在类级别配置 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 属性/code> 来实现你想要的.如果您需要将参数传递给 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 序列化设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆