2015-08-09 47 views
1

我想解析來自Instagram API的JSON數據,並且遇到了解析子元素的問題。例如,一個Instagram的迴應是這樣的:在C#子成員中解析JSON

{ 
    "pagination": { 
     "next_url": "https://api.instagram.com/v1/users/273112457/followed-by?access_token=1941825738.97584da.3242609045494207883c900cbbab04b8&cursor=1439090845443", 
     "next_cursor": "1439090845443" 
    }, 
    "meta": { 
     "code": 200 
    }, 
    "data": [ 
     { 
      "username": "ohdyxl", 
      "profile_picture": "https://igcdn-photos-e-a.akamaihd.net/hphotos-ak-xfp1/t51.2885-19/11093019_661322517306044_2019954676_a.jpg", 
      "id": "1393044864", 
      "full_name": "只有你和我知道" 
     }, 
     { 
      "username": "dpetalco_florist", 
      "profile_picture": "https://igcdn-photos-a-a.akamaihd.net/hphotos-ak-xtf1/t51.2885-19/11192809_930052080349888_1420093998_a.jpg", 
      "id": "1098934333", 
      "full_name": "D'petalco florist" 
     } 
    ] 
} 

我的代碼如下:

dynamic d = JObject.Parse(response); 
foreach (var result in d["data"]) 
{ 
    string userName = (string)result["username"]; 
    list.Add(userName); 
} 

這部分作品完美,但是當我嘗試提取分頁,我得到一個孩子的錯誤訪問錯誤。

我的代碼如下:

foreach (var res in d["pagination"]) 
{ 
    string nexturl = (string)res["next_url"]; 
    string nextcursor = (string)res["next_cursor"]; 
} 

我如何可以提取 「分頁」 在C#中next_url和next_curosr?謝謝。

回答

2

不像data屬性值,pagination屬性值是不是一個數組,所以你不需要foreach循環這裏:

var res = d["pagination"]; 
string nexturl = (string)res["next_url"]; 
string nextcursor = (string)res["next_cursor"]; 

使用或不使用中間變量res

string nexturl = (string)d["pagination"]["next_url"]; 
string nextcursor = (string)d["pagination"]["next_cursor"];