我如何选择退出JSON合同解析程序

时间:2016-08-17 13:14:56

标签: c# .net json json.net

我们有一个Json.NET设置,它将合约解析器设置为CamelCasePropertyNamesContractResolver。但是,对于某些类型,我想选择退出camelCasing行为。是否可以通过某种方式注释这些类型来实现这一目标?

1 个答案:

答案 0 :(得分: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"
}

小提琴: