How to parse JSON in C ?
How to convert JSON text into objects using C# - Stack Overflow
Json to c# object
Loosely defined JSON and how to design C# Model for it
Videos
So, I am planning to make the weather app which gives weather from API . I got the response (JSON) using cURL library but stuck on parsing that response into getting useful things like get weather report of user input places.
To create a class off a json string, copy the string.
In Visual Studio, in the menu at the top, click Edit > Paste special > Paste Json as classes.
Install Newtonsoft.Json via Nuget
Paste the following code into your project, "jsonString" being the variable you wish to deserialize :
Rootobject r = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(jsonString);Don't forget to rename Rootobject to be more descriptive eg
ILoveTheSmellOfNapalmInTheMorning-that was a joke
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)
since I really rare use strong type language especially when handling response from an API, my question is do I have to make a brand new class that define what the response from an API?