s

C# serialize list of objects to json edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 17 September 2020 | 2149

I have an object model that looks like the object below, how can I serialize the list to JSON.

public class Country
{
    public int Id { get; set; }
    public int Code { get; set; }
    public String Name { get; set; }
}

You can serialize the list of JSON using Newtonsoft.Json. Check the code below.

List<country> lstCountries = new Country().Get();
String countryJson = Newtonsoft.Json.JsonConvert.SerializeObject(lstCountries);

Here is the serialized JSON code.

[{"Id":1,"Code":91,"Name":"India"},{"Id":2,"Code":86,"Name":"China"},{"Id":3,"Code":1,"Name":"USA"},{"Id":4,"Code":91,"Name":"India"},{"Id":5,"Code":7,"Name":"Russia"},{"Id":6,"Code":91,"Name":"India"},{"Id":7,"Code":86,"Name":"China"}]