0

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.

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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. schema of your json string

foreach(dynamic item in jsonObj.item.package_data)
{
     //item.tracking_no;
     //item.package_reference
}

1 Comment

it is working, but you should change jsonObj.item.package_data to jsonObj.data.package_data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.