mdieod
mdieod

Reputation: 49

Get JSON child element value

I'm trying to get spuCode from this JSON:

{
  "msg": "success",
  "state": 0,
  "data": {
    "result": {
      "spuCode": "541426110605",
      "productName": "纯黑色斜纹面料铅笔裤百搭大码小脚裤弹力打底裤休闲裤子女",
      "productTitle": null,
      "spuImgs": [
        "https://cbu01.alicdn.com/img/ibank/2016/276/468/3618864672_1742354982.jpg",
        "https://cbu01.alicdn.com/img/ibank/2016/793/372/3617273397_1742354982.jpg",
        "https://cbu01.alicdn.com/img/ibank/2016/726/552/3617255627_1742354982.jpg",
        "https://cbu01.alicdn.com/img/ibank/2017/521/101/4624101125_1742354982.jpg",
        "https://cbu01.alicdn.com/img/ibank/2017/070/749/4580947070_1742354982.jpg"
      ],
      "upAndDown": 1,
      "updateTime": 1537096913958,
      "platform": "ALIBABA",
      "skus": [
        {
          "skuCode": "3488434133172",
          "sellPrice": 3900,
          "sellableNum": 905,
          "productProps": [
            {
              "propId": 7590793702270582000,
              "valueId": 5453504708925905000,
              "propName": "颜色",
              "valueName": "纯黑色(相同面料)"
            },
            {
              "propId": 9000005669393888000,
              "valueId": 6217370164147047000,
              "propName": "尺码",
              "valueName": "XXL"
            }
          ],

As you can see there is Parent data with child result so I added this code:

string sp = "";
var obj = Newtonsoft.Json.Linq.JObject.Parse(responseFromServer);
foreach (JObject child in obj["data"]["result"].OfType<JObject>())
{
    sp = child["spuCode"].ToString();
    MessageBox.Show(sp);
}

But it never triggers MessageBox.Show what am I missing here?

Upvotes: 1

Views: 107

Answers (1)

Hossein
Hossein

Reputation: 3113

result isn't an array so there is no need for foreach.

Try SelectToken method like this:

var spuCode = (string)obj.SelectToken("data.result.spuCode");

Upvotes: 4

Related Questions