简体   繁体   中英

Extracting value from json string C#

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.

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

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. json字符串的模式

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM