Reputation: 1288
My json string is as follows:
{
"data": {
"order_reference": "7000016543",
"package_data": [
{
"tracking_no": "34144582723408",
"package_reference": "7000016543"
}
]
},
"success": true
}
How do I get tracking_no from this json.
I tried using
dynamic jsonObj = JsonConvert.DeserializeObject(bytesAsString);
and then
foreach (var obj in jsonObj.items)
{
}
but it only yields order reference.
Upvotes: 0
Views: 100
Reputation: 1942
You can create Types for your JSON:
namespace Example
{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public class MyObject
{
[JsonProperty("data")]
public Data Data { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
}
public class Data
{
[JsonProperty("order_reference")]
public string OrderReference { get; set; }
[JsonProperty("package_data")]
public PackageDatum[] PackageData { get; set; }
}
public class PackageDatum
{
[JsonProperty("package_reference")]
public string PackageReference { get; set; }
[JsonProperty("tracking_no")]
public string TrackingNo { get; set; }
}
}
then you can deserialize using JsonConvert.Deserialize<MyObject>(input);
Upvotes: 2
Reputation: 837
the problem about your code is: there is no collection on your root json object. I mean it is not an object. Since it is just an object and it's child you can access is directly. And then you have a collection package_data. So you can go for loop in it.
Here is the schema of your json data.
foreach(dynamic item in jsonObj.item.package_data)
{
//item.tracking_no;
//item.package_reference
}
Upvotes: 0