JSON standards vs C# naming standards

Anyone that has coded in C# for any amount of time is accustom to seeing property names in Pascal case such as the example below…

public class MyClass {
    public string MyString { get;set; }
    public int MyInt { get;set; }
}

Which will serialize the class as follows…

{ "MyString":"hello world","MyInt":1 }

Some of your JSON gurus would tell you that the properties for a JSON object should really be in camel case instead of pascal (examples). So we are in-between worlds here trying to find something that will work for everyone.

Our first option would be to use the JsonPropertyAttribute to specify the name for the property during serialization such as below…

public class MyClass {
    [JsonProperty("myString")]
    public string MyString { get;set;}
    [JsonProperty("myInt")]
    public int MyInt { get;set; }
}

Option two would be to make a change in the serialization options such as below…

    MyClass obj = new MyClass()
    {
        MyInt = 1,
        MyString = "hello world";
    };
    var jsonSettings = new JsonSerializerSettings
    {
        ContractResolver = new CamelCasePropertyNamesContractResolver()
    };
    string json = JsonConvert.SerializeObject(obj, Formatting.Indented, jsonSettings);

Both of which will give us our desired output of…

{
  "myString": "hello world",
  "myInt": 1
}

This may be most useful when working within the WebAPI technology of asp.net. If you would like to set the serializer to camelcase for the entire api, you would would need to add the below line to your Application_Start() method within your global.asax

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Advertisements

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 )

Google+ photo

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

Connecting to %s