2017-08-28 148 views
0

如何在List<String>中抓取所有標記
這裏是JSON字符串:C#提取使用Newtonsoft.Json的json數組對象

{ 
    "error": null, 
    "jsonrpc": "2.0", 
    "id": 0, 
    "result": { 
     "paginator": null, 
     "cat_count": {}, 
     "last_post_date": 386623075949839, 
     "post_list": [ 
      { 
       "hc": false, 
       "p2": 4, 
       "token": "LnARJZCmt" 
      }, 
      { 
       "hc": false, 
       "p2": 4, 
       "token": "BuD2oIs3N" 
      }, 
      { 
       "p2": 4, 
       "token": "89NaBsAha", 
       "hc": false, 
      } 
     ], 
     "error": 0 
    } 
} 

我使用Newtonsoft.Json
這裏是我的嘗試:

var obj = JObject.Parse(json); 
    string next_search_val = (string)obj["result"]["last_post_date"]; 
    var tokens = obj["result"]["post_list"]["token"]; > Fix this line for me > I have error here 

回答

2

我會用

var tokens = JObject.Parse(json) 
       .SelectTokens("$..token") 
       .Select(x => (string)x) 
       .ToList(); 

編輯

同樣的事情,而不JsonPath

var tokens = JObject.Parse(json) 
       .Descendants() 
       .OfType<JProperty>() 
       .Where(x => x.Name == "token") 
       .Select(x => x.Value) 
       .ToList(); 

EDIT 2

最接近您嘗試

var tokens = JObject.Parse(json)["result"]["post_list"] 
       .Select(x => (string)x["token"]) 
       .ToList(); 
+0

$ ..>那是什麼意思呢? – MoonLight

+0

@MoonLight [用JSONPath查詢JSON](https://www.newtonsoft.com/json/help/html/QueryJsonSelectTokenJsonPath.htm) –

+0

欣賞它並感謝。 – MoonLight