Tuesday, January 8, 2019

Load JSON text into class object in c#

How can I convert the following Json Response to a C# object?

{ "err_code": "0", "org": "CGK", "des": "SIN", "flight_date": "20120719",
"schedule":
[
["W2-888","20120719","20120719","1200","1600","03h00m","737-200","0",[["K","9"],["F","9"],["L","9"],["M","9"],["N","9"],["P","9"],["C","9"],["O","9"]]],
["W2-999","20120719","20120719","1800","2000","01h00m","MD-83","0",[["K","9"],["L","9"],["M","9"],["N","9"]]]

] }

Answer: 

First create a class to represent your json data.

public class MyFlightDto
{
    public string err_code { get; set; }
    public string org { get; set; } 
    public string flight_date { get; set; }
    // Fill the missing properties for your data
}
Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.
var jsonInput = "{ org:'myOrg',des:'hello'}"; 
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Or Use JavaScriptSerializer to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer  = jsonSerializer.Deserialize<Customer >(jsonInput)
Assuming you want to convert it to a Customer classe's instance. Your class should looks similar to the JSON structure (Properties)

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...