JSON love to be camelCased, while the C# Model class hates it. This comes down to coding style, which is – among developers – taken more seriously than politics and religion.
But fear not, with Newtonsoft (or is it newtonSoft – or NewtonSoft?) you have more than one weapon in the arsenal that will satisfy even the most religious coding style troll.
OPTION 1: THE CamelCasePropertyNamesContractResolver
The CamelCasePropertyNamesContractResolver is used alongside JsonSerializerSettings the serializing objects to JSON. It will – as the name implies – resolve any property name into a nice camelCasing:
// An arbitrary class public MyModelClass { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } } // The actual serializing code: using Newtonsoft.Json; using Newtonsoft.Json.Serialization; var myModel = new MyModelClass() { FirstName = "Arthur", LastName = "Dent", Age = 42 }; var serializedOutput = JsonConvert.SerializeObject( myModel, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() } );
The resulting JSON string will now be camelCased, even when the MyModelClass properties are not:
{ firstName: 'Arthur', lastName: 'Dent', age: 42 }
OPTION 2: USING THE JsonProperty ATTRIBUTE:
If you own the model class you can control not only how the class is serialized, but also how it is deserialized by uding the JsonProperty attribute:
using Newtonsoft.Json; public MyModelClass { [JsonProperty("firstName")] public string FirstName { get; set; } [JsonProperty("lastName")] public string LastName { get; set; } [JsonProperty("age")] public int Age { get; set; } }
Both the JsonConvert.SerializeObject and the JsonConvert.DeserializeObject<T> methods will now use the JsonProperty name instead of the model class property name.
MORE TO READ:
- Newtonsoft documentation
- Serialization using ContractResolver from Newtonsoft
- JsonPropertyAttribute name from Newtonsoft
- Deserialize XML array to string[] and how to allow JSON to be deserialized into the same POCO class by briancaos
- C# Using Newtonsoft and dynamic ExpandoObject to convert one Json to another by briancaos