Newtonsoft JsonSerializer - Lower case or customize properties name

C# Apr 24, 2020 Viewed 10.8K Comments 0

In C#, we can use Newtonsoft.Json framework to convert the object to a JSON string. JsonConvert.SerializeObject method, which will serialize the specified object to a JSON string. We are able to customize property names to any format, such as lower case, upper case, camel case, and so on.

For example, there is a Person class as follow.

class Person
{
    public string UserName { get; set; }
    public int Age { get; set; }
}

1. Using JsonSerializerSettings

With CamelCasePropertyNamesContractResolver, we can resolve member mappings for a type, camel casing property names. 

static void Main(string[] args)
{
    Person person = new Person();
    person.UserName = "Google";
    person.Age = 20;

    var serializerSettings = new JsonSerializerSettings();
    serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    var json = JsonConvert.SerializeObject(person, serializerSettings);
    Console.WriteLine(json);
}

Output

{"userName":"Google","age":20}

2. Using JsonProperty

Used by JsonSerializer to resolve a JsonContract for a given Type.

In the class of Person, add JsonProperty and specify any name.

class Person
{
    [JsonProperty("user_name")]
    public string UserName { get; set; }

    [JsonProperty("age")]
    public int Age { get; set; }
}

SerializeObject

static void Main(string[] args)
{
    Person person = new Person();
    person.UserName = "Google";
    person.Age = 20;

    var json = JsonConvert.SerializeObject(person);
    Console.WriteLine(json);
}

Output

{"user_name":"Google","age":20}
Updated Apr 24, 2020