C# Newtonsoft camelCasing the serialized JSON output

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:

 

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.