how to work with json object in c# how to work with json object in c# json json

how to work with json object in c#


After you get a json string you need to deserialize it.Use this site to generate you model

http://json2csharp.com/

you will get some classes like

public class ProductionCompany{    public string name { get; set; }    public int id { get; set; }}public class RootObject{    public double popularity { get; set; }    public List<ProductionCompany> production_companies { get; set; }}

then you can call

var json = "...yout json string..."RootObject obj = JsonConvert.DeserializeObject<RootObject >(json);

and you can use the data retreived easily


First Define the Classes as below :

public class ProductionCompany{    public string name { get; set; }    public int id { get; set; }}public class Item{    public double popularity { get; set; }    public List<ProductionCompany> production_companies { get; set; }}

You can then use jsonSerializer to convert your JSON to class object

    string jsonInput="your Json string";     JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();    Item item= jsonSerializer.Deserialize<Item>(jsonInput)

Now your data can easily be retrived from object item, something like this

  foreach (var productioncompany in item.Production_Companies)    {       productioncompany.Name;         productioncompany.id;    }


The easiest way to do this is to create a class that matches your JSON, deserialize the JSON and then access the properties through the created object.

For example:

public class Companies(){  public double Popularity { get; set; }  public List<ProductionCompany> Production_Companies { get;set; }  public Companies(){    Production_Companies  = new List<ProductionCompany>();  }}public class ProductionCompany(){   public string Name {get;set;}   public int Id {get;set;}}

Then you deserialize with JSON.Net

  var myObject = JsonConvert.DeserializeObject<Companies>(jsonString);

And access the Properties

foreach (var company in myObject.Production_Companies){   company.Name;  //do something...}