behzad razzaqi
behzad razzaqi

Reputation: 147

How can i parse json in c# with newtonjson?

I'm new in c# and have this json string:

"{\"Result\":0,\"Packages\":[{\"Count\":5.0,\"Price\":100000},{\"Count\":10.0,\"Price\":170000},{\"Count\":20.0,\"Price\":300000},{\"Count\":50.0,\"Price\":600000},{\"Count\":100.0,\"Price\":900000}],\"IsArbitrary\":true}"


try parse that string with this code:

dynamic dynObj = JsonConvert.DeserializeObject(html);


but i want access to for example array index zero or array index one,how can i write code for that purpose?thanks.

Upvotes: 0

Views: 71

Answers (1)

Zein Makki
Zein Makki

Reputation: 30022

Don't use dynamic unless there is no other option to solve your problem. Here is how you can create a type to map your data:

private struct DataHolder
{
    public decimal result { set; get; }
    public Package[] Packages { set; get; }
    public bool IsArbitrary { set; get; }
}

private struct Package
{
    public decimal Count { set; get; }
    public decimal Price { set; get; }
}

static void Main(string[] args)
{
    string html = "{\"Result\":0,\"Packages\":[{\"Count\":5.0,\"Price\":100000},{\"Count\":10.0,\"Price\":170000},{\"Count\":20.0,\"Price\":300000},{\"Count\":50.0,\"Price\":600000},{\"Count\":100.0,\"Price\":900000}],\"IsArbitrary\":true}";

    DataHolder data = JsonConvert.DeserializeObject<DataHolder>(html);

    foreach(var package in data.Packages)
    {
       // do something with package.Count or package.Price
    }
}

Then you have a static object where you can access Packages and loop over it.

Upvotes: 2

Related Questions