Newtonsoft.Json.JsonConvert In C#

Introduction

The Newtonsoft.Json namespace provides classes that are used to implement the core services of the framework.

It converts an object to and from JSON. 

To demonstrate, we have taken an instance of the customer and the orders placed.

Let's get started... 

Step 1

Add two classes:

public class MyJson  
{  
   public int customer_id { get; set; }  
   public string customer_name{ get; set; }  
   public Order orders{ get; set; }  
}  
public class Order  
{  
   public string[] ids = new string[] {"1001","1005"};  
   //public string[] ids = new string[] { }; to send an empty array  
}

Step 2

Create the Json Format to send requests and get a response.

using Newtonsoft.Json;  
public class Response  
{    
   MyJson myJson = new MyJson();   
   myJson.customer_id = "C1";  
   myJson.customer_name="Mathew"   
   string json1 = JsonConvert.SerializeObject(myJson);  
   var data1 = new StringContent(json1, Encoding.UTF8, "application/json");  
   var url = "Your Request ApiUrl";  
   var client = new HttpClient();  
   var response = client.PostAsync(url, data1);  
   dynamic result = response.Result.Content.ReadAsStringAsync().Result;  
   var jObject = JsonConvert.DeserializeObject(result);  
   
   foreach (var obj in jObject.searchResults.results)  
   {  
       // Your logic.  
   }   
}

Note

JsonConvert.SerializeObject (Serializes the specified object to a JSON string. Return Type -string).

JsonConvert.DeserializeObject (Deserializes the JSON to a .NET object. Return Type object).

The var keyword is early bounded.

The dynamic keyword is late bounded and everything happens at runtime.

Happy Learning...