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:
  1. public class MyJson  
  2. {  
  3.    public int customer_id { getset; }  
  4.    public string customer_name{ getset; }  
  5.    public Order orders{ getset; }  
  6. }  
  7. public class Order  
  8. {  
  9.    public string[] ids = new string[] {"1001","1005"};  
  10.    //public string[] ids = new string[] { }; to send an empty array  
  11. }  
Step 2
 
Create the Json Format to send requests and get a response.
  1. using Newtonsoft.Json;  
  2. public class Response  
  3. {    
  4.    MyJson myJson = new MyJson();   
  5.    myJson.customer_id = "C1";  
  6.    myJson.customer_name="Mathew"   
  7.    string json1 = JsonConvert.SerializeObject(myJson);  
  8.    var data1 = new StringContent(json1, Encoding.UTF8, "application/json");  
  9.    var url = "Your Request ApiUrl";  
  10.    var client = new HttpClient();  
  11.    var response = client.PostAsync(url, data1);  
  12.    dynamic result = response.Result.Content.ReadAsStringAsync().Result;  
  13.    var jObject = JsonConvert.DeserializeObject(result);  
  14.    
  15.    foreach (var obj in jObject.searchResults.results)  
  16.    {  
  17.        // Your logic.  
  18.    }   
  19. }  
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...