2

I want to camel case specific properties of an object using Json.NET rather than all of the properties.

I have an object like this:

class A {
    public object B { get; set; }
    public object C { get; set; } // this property should be camel cased
}

I want it to get serialized to this:

{ B: 1, c: 2 }

I came across this post about camel casing all properties unconditionally, which is done using:

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var json = JsonConvert.SerializeObject(a, settings);

But I couldn't find a counter-part question for camel casing a specific property. How is this done?

pushkin
  • 9,575
  • 15
  • 51
  • 95
  • 1
    Possible duplicate of [How can I change property names when serializing with Json.net?](https://stackoverflow.com/questions/8796618/how-can-i-change-property-names-when-serializing-with-json-net) – maccettura May 10 '18 at 23:05
  • @maccettura This isn't really a duplicate. He's asking the more general question about just changing property names to something else. I'm talking about camel casing them. – pushkin May 10 '18 at 23:10
  • 1
    @pushkin Yet the second "strategy" is an exact duplicate of that question. I don't see how it's "less preferable" nor why you think that – Camilo Terevinto May 10 '18 at 23:13
  • @CamiloTerevinto Though the second, less optimal, strategy may be a duplicate of the linked answer, my question is not a duplicate, nor is the more optimal strategy from my answer. – pushkin May 10 '18 at 23:14
  • 1
    Then how about duplicate of [this one](https://stackoverflow.com/questions/42092359/jsonserializersettings-to-change-case-of-property-name-but-not-name-of-property)? – Camilo Terevinto May 10 '18 at 23:21
  • @CamiloTerevinto Yup, this is a dup, then. I missed that one in my searches. Thanks – pushkin May 10 '18 at 23:24
  • 1
    I cannot blame you though, that was the 6th Google result, after duplicates of the one @maccettura linked – Camilo Terevinto May 10 '18 at 23:25
  • @CamiloTerevinto Though now that I look more closely, he's technically asking about camelcasing an entire object, which is technically different. Or is that a strech? – pushkin May 10 '18 at 23:27
  • I would consider " I do not want to change case of those properties." the same as "I want to camel case specific properties", but that's me – Camilo Terevinto May 10 '18 at 23:28

1 Answers1

3

You can apply JsonPropertyAttribute's NamingStrategyType to the field that you want to camel case:

class A 
{
    [JsonProperty(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
    public object C { get; set; }
}

Or you can specify the name of the Property directly:

class A 
{
    [JsonProperty("c")]
    public object C { get; set; }
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
pushkin
  • 9,575
  • 15
  • 51
  • 95