但不更改属性名称的大小写

但不更改属性名称的大小写

本文介绍了JsonSerializerSettings更改属性名称的大小写,但不更改属性名称的大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下设置来设置班级属性的骆驼壳.

I am using below settings for camel casing of my class property.

JsonSerializerSettings settings = new JsonSerializerSettings()
        {
            ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
        };

对象中的某些属性属于某些其他类类型.我不想更改这些属性的大小写.

Some of the property in the object are of some other class type. I do not want to change case of those properties.

例如:

Public Class CaseToChange
{
    public string StringProperty{get;set;} //Change to camelCase
    public SomeOtherType OtherTypeProperty{get;set;} //Change name of this to camelCase but not property name of "SomeOtherType"

}

如何使用JsonSerializerSettings实现此目的?

How to achieve this with JsonSerializerSettings?

推荐答案

如果您可以修改类型以添加​​ Json.NET序列化属性,最简单的方法是添加 [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] 到您的CaseToChange类型:

If you can modify your types to add Json.NET serialization attributes, the easiest thing to do would be to add [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))] to your CaseToChange type:

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
public class CaseToChange
{
    public string StringProperty { get; set; } //Change to camelCase
    public SomeOtherType OtherTypeProperty { get; set; } //Change name of this to camelCase but not property name of "SomeOtherType"
}

(或者,如果您使用的Json.NET版本低于9.0.1,则将[JsonProperty("camelCaseName")]添加到每个属性中,如此答案.)

(Or, if you are using a version of Json.NET earlier than 9.0.1, add [JsonProperty("camelCaseName")] to each property as in this answer.)

如果您不能修改类型,而只能通过序列化程序设置来驼峰写CaseToChange的属性,则可以创建自定义合同解析器,它返回CaseToChange的驼峰式名称和其他类型的未修改名称.以下是技巧:

If you cannot modify the type and must camel-case the properties of CaseToChange only through serializer settings, you can create a custom contract resolver that returns camel-cased names for CaseToChange and unmodified names for other types. The following does the trick:

public class OverrideContractResolver : ContractResolverDecorator
{
    readonly Dictionary<Type, IContractResolver> overrides;

    public OverrideContractResolver(IEnumerable<KeyValuePair<Type, IContractResolver>> overrides, IContractResolver baseResolver)
        : base(baseResolver)
    {
        if (overrides == null)
            throw new ArgumentNullException();
        this.overrides = overrides.ToDictionary(p => p.Key, p => p.Value);
    }

    public override JsonContract ResolveContract(Type type)
    {
        IContractResolver resolver;
        if (overrides.TryGetValue(type, out resolver))
            return resolver.ResolveContract(type);
        return base.ResolveContract(type);
    }
}

public class ContractResolverDecorator : IContractResolver
{
    readonly IContractResolver baseResolver;

    public ContractResolverDecorator(IContractResolver baseResolver)
    {
        if (baseResolver == null)
            throw new ArgumentNullException();
        this.baseResolver = baseResolver;
    }

    #region IContractResolver Members

    public virtual JsonContract ResolveContract(Type type)
    {
        return baseResolver.ResolveContract(type);
    }

    #endregion
}

然后使用以下设置进行序列化:

Then serialize with settings as follows:

var settings = new JsonSerializerSettings
{
    ContractResolver =
        new OverrideContractResolver(
            new Dictionary<Type, IContractResolver> { { typeof(CaseToChange), new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() } },
            new Newtonsoft.Json.Serialization.DefaultContractResolver()),
};

生成的JSON如下所示:

And the resulting JSON will look like:

{
  "stringProperty": "string property",
  "otherTypeProperty": {
    "FooProperty": "foo",
    "BarProperty": 101
  }
}

示例小提琴.

为了获得最佳性能,您可能需要缓存合同解析器的实例.

For optimal performance you may want to cache instances of the contract resolver.

这篇关于JsonSerializerSettings更改属性名称的大小写,但不更改属性名称的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:18