Convert Json to C# Object

How to Convert Json string to C# object using Newtonsoft

September 17, 2020

In this article we will cover how to Convert or Deserialize Json string to class object in c# using Newtonsoft library.

Newtonsoft.json is a JSON framework for .NET. Using it we can Serialize and deserialize any .NET object.

Country.cs

public class Country
{
    public int Country_Id { getset; }
    public string Country_Title { getset; }
    public string Country_Code { getset; }
    public bool Country_Active { getset; }
}

Sample Country Json

Create countries.json and add below sample data.

[
  {
    "Country_Id": 1,
    "Country_Title""Afghanistan",
    "Country_Code""AF",
    "Country_Active"true
  },
  {
    "Country_Id": 2,
    "Country_Title""Aland Islands",
    "Country_Code""AX",
    "Country_Active"true
  },
  {
    "Country_Id": 3,
    "Country_Title""Albania",
    "Country_Code""AL",
    "Country_Active"true
  },
  {
    "Country_Id": 4,
    "Country_Title""Algeria",
    "Country_Code""DZ",
    "Country_Active"true
  }
]

Convert Json To C# Object

List<Countrycountries = new List<Country>();
using (StreamReader sr = new StreamReader(Server.MapPath("~/countries.json")))
{
    countries = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Country>>(sr.ReadToEnd());
}

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...