31

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"]]]
    ]
}
Brian Rogers
  • 118,414
  • 30
  • 277
  • 278
Vishwajeet
  • 1,365
  • 2
  • 18
  • 33
  • if you are using an MVC there is a lot that is does out of the box to support that conversion. You can also check out this link: http://msdn.microsoft.com/en-us/library/bb410770.aspx – Glenn Ferrie Jun 29 '12 at 11:07
  • 1
    See this post: http://stackoverflow.com/questions/6620165/how-to-parse-json-in-c – Jocke Jun 29 '12 at 11:08
  • 1
    i face problem to build class for that json reponse can any one build the class for that json response – Vishwajeet Jun 29 '12 at 11:21
  • Possible duplicate of [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – StayOnTarget Sep 19 '18 at 12:54

6 Answers6

114

To create a class off a json string, copy the string.

In Visual Studio, click Edit > Paste special > Paste Json as classes.

Ole EH Dufour
  • 2,566
  • 4
  • 22
  • 40
  • 15
    It's amazing how everyone just skips past this answer. Upvoted. – Robert Oschler Jan 06 '18 at 02:24
  • 3
    Yes, I think this really what was asked for at the time. It was kind of a roundabout thing in VS2012 (see here: https://stackoverflow.com/questions/18526659/how-to-show-the-paste-json-class-in-visual-studio-2012-when-clicking-on-paste) Now in VS2017, very straightforward. – Ben Butzer Feb 16 '18 at 19:54
  • 2
    Extremely useful and when doing a conversion using JsonConvert you may have to create the delegate as an array. In my case this is what I had to do in order to convert the JSON string to a class. JsonConvert.DeserializeObject(FootnoteJSON.Value) – Brandon Jun 27 '18 at 19:55
  • I don't think this is what was asked – KansaiRobot Feb 08 '19 at 08:01
  • 1
    I recently found the need to work with JSON and came across this site https://json2csharp.com/ and now I discover that VS does it for you. Good information to have. – Zath Jun 28 '21 at 18:39
60

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)

Shyju
  • 206,216
  • 101
  • 402
  • 492
52

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Performance Comparison To Other JSON serializiation Techniques enter image description here

Talha
  • 18,147
  • 8
  • 47
  • 64
  • 1
    Hi,Talha my problem is i am not able to built datastructure of a class which holds this json result – Vishwajeet Jun 29 '12 at 11:30
  • 1
    @Vish: You should have main class e.g; FlightInfo with properties, one property should be the List of Schedule e.g; List. Schedule is the 2nd class which has also some properties. See your json string properly – Talha Jun 29 '12 at 11:39
  • @Talha:Ya but schedule contains what type of properties because in schedule there are arrays inside array – Vishwajeet Jun 29 '12 at 11:49
  • This doesn't answer the question – Ole EH Dufour Jan 13 '18 at 18:49
4

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

Islam
  • 119
  • 1
  • 1
  • Great, another similar useful online tool, which might help, here it is: https://www.minify-beautify.com/json-to-csharp-class-online/ Thanks – Vikas Lalwani Aug 20 '21 at 07:40
1

This will take a json string and turn it into any class you specify

public static T ConvertJsonToClass<T>(this string json)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Deserialize<T>(json);
    }
ff0000e2
  • 417
  • 5
  • 14
0
class Program
{
    static void Main(string[] args)
    {
        var res = Json; //Json that has to be converted

        Response resp = new Response();
        resp = JsonSerializer.Deserialize<Response>(res);

        Console.WriteLine(res);
    }
}

public class Response
{
    public bool isValidUser { get; set; }
    public string message { get; set; }
    public int resultKey { get; set; }
}
elena.kim
  • 937
  • 4
  • 11
  • 21