Hooman Hooman - 3 months ago 5
JSON Question

how to work with json object in c#

i am working with a json that it comes from an api
so here is what i am talking about:

{"popularity":3.518962,
"production_companies":[{"name":"valu1","id":4},{"name":"valu2","id":562},
{"name":"valu13","id":14654},{"name":"valu4", "id":19177},{"name":"valu5","id":23243}]}


i already can return value of "popularity"

for example i need to know how can i access value of "name" and which "name" is it?

i tried to convert it to an array but didn't work or i did something wrong
please help

my class Content:

public class GetData
{

public string popularity{set;get;}
public object production_companies{set;get;}

public GetData GetBasic(string ID){
var json = @"{'popularity':3.518962,
'production_companies':[{'name':'valu1','id':4},{'name':'valu2','id':562},
{'name':'valu13','id':14654},{'name':'valu4', 'id':19177},
{'name':'valu5','id':23243}
]
}";

GetData Data = JsonConvert.DeserializeObject<GetData>(json);
return Data;

}


here is what i done

@{
var arr = Item.production_companies.ToString().Substring(1, (Item.production_companies.ToString().Length - 2)).ToArray();
foreach(var a in arr){
@a.name
}
}

Answer

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

Comments