+977-9849845061

Deserialize JSON data from External URL to Model using Newstonsoft.JSON in ASP.NET C#

1626total visits.

When we want to convert to and from a JSON string, the SerializeObject() and DeserializeObject()methods on JsonConvert provide an easy-to-use wrapper over JsonSerializer. SerializeObject() and DeserializeObject() both have overloads that take a JsonSerializerSettings object. 

When we want to use data from other websites and JSON URLs, we can use JsonConvert.DeserializeObject() or JsonConvert.SerializeObject() to serialize and deserialize the JSON String

The most convenient and fast method of converting between JSON text and a .NET object is using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent and back again by mapping the .NET object property names to the JSON property names.

When we want to convert to and from a JSON string, the SerializeObject() and DeserializeObject()methods on JsonConvert provide an easy-to-use wrapper over JsonSerializer.

SerializeObject() and DeserializeObject() both have overloads that take a JsonSerializerSettings object.

 

Let’s consider an example where we have a case to fetch and parse data from other Websites using JSON URL.

In this case, let’s assume the data source is JSON URL as http://mysafeinfo.com/api/data?list=englishmonarchs&format=json.

Our requirement is to

  • Read data from JSON URL.
  • Map the JSON Data to View Model in C#.
  • Display all data to Views in tabular form.

Step 1: Create ViewModel to bind data and pass to Views

Let’s Create a ViewModel named EnglishMonarchSample with following properties.

 

Step 2: Download JSON Content and Deserialize to JSON.

Explanation:

  • WebClient httpClient = new WebClient()
    • Provides common methods for sending data to and receiving data from a resource identified by a URI.
  • httpClient.DownloadString(“URL”)
    • Downloads the resource with the specified URI to a local file.
  • JsonConvert.DeserializeObject<EnglishMonarchSample>(jsonData)
    • This line of code will Desearilize the JSON Data downloaded using httpClient.DownloadString() and then map convert each row of values into IEnumerable Photos.

Step 3: List data using ViewModel

 

The above three easy steps will now read the JSON data from URL, convert to JSON format and bind to ViewModel in ASP.NET C# Applications.

 

Source Code and Project File : https://github.com/nishanaryal/ASP.NET-MVC

 

 

 

 

 

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...