In this article I will explain with an example, how to use Newtonsoft library in ASP.Net Core.
ASPSnippets Test API
The following API will be used in this article.
The API returns the following JSON.
[
{
"CustomerId": 1,
"Name": "John Hammond",
"Country": "United States"
},
{
"CustomerId": 2,
"Name": "Mudassar Khan",
"Country": "India"
},
{
"CustomerId": 3,
"Name": "Suzanne Mathews",
"Country": "France"
},
{
"CustomerId": 4,
"Name": "Robert Schidner",
"Country": "Russia"
}
]
Installing Newtonsoft package using Nuget
Model
The Model class consist of the following properties.
public class CustomerModel
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Net;
using Newtonsoft.Json;
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, first the JSON string is downloaded from an API using
DownloadString method of the
WebClient class.
Then, JSON string is converted into a Generic List collection of CustomerModel class object using DeserializeObject method of JsonConvert class.
Finally, View is returned.
public class HomeController : Controller
{
public IActionResult Index()
{
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string json = (new WebClient()).DownloadString("https://raw.githubusercontent.com/aspsnippets/test/master/Customers.json");
List<CustomerModel> customers = JsonConvert.DeserializeObject<List<CustomerModel>>(json);
return View();
}
}
Screenshot
Downloads