2016-08-17 25 views
3

我們有一個Json.NET設置程序,它將合同解析器設置爲CamelCasePropertyNamesContractResolver。但是,對於某些類型,我想選擇退出camelCasing行爲。是否有可能通過某種方式註釋這些類型?如何退出JSON合約解析器

+1

您使用的是什麼版本的.NET? – Delosdos

+0

是任何用途:http://stackoverflow.com/questions/19956838/force-camelcase-on-asp-net-webapi-per-controller你可以設置每個控制器的解析器。 – Delosdos

+1

@Delosdos這是針對.NET 4.6庫的,不適用於特定的Web框架。 – ChaseMedallion

回答

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