从C#中的JSON中检索特定值

时间:2018-03-17 09:54:03

标签: c# json parsing

我需要从下面的JSON中获取值,例如如何在Info中索引Id?

整个JSON由许多匹配组成,这只是一个Id 5aa891cd1e1422452e8b4567,这是一个匹配的结构。

我尝试:

var jsonDATA = JObject.Parse(data);

foreach (var e in jsonDATA["events"]) {
    //in this step, the result is JSON below
    var id = e["info"]["id"];` // error: cannot access child value on newtonsoft json linq jproperty
}

有什么想法吗?

{"5aa891cd1e1422452e8b4567": {
      "info": {
        "id": "5aa891cd1e1422452e8b4567",
        "event_id": "58911142245284567",
        "name": "Santos Laguna vs Queretaro",
        "sport": "Soccer",
        "league": "Mexico Cup",
        "period": "Finished",
        "score": "1:0",
        "status": "Live",
        "start_time": "2018.03.14 03:06:53",
        "state": 1017,
        "state_name": "Fulltime",
        "minute": 90,
        "safe": false,
        "safe2": false,
        "blocked": false,
        "stop": false
      },
      "stats": {
        "home": {
          "name": "Santos Laguna",
          "color": "",
          "position": "",
          "on_target": "",
          "off_target": "",
          "attacks": "",
          "dangerous_attacks": "",
          "possession": "",
          "goals": 1,
          "corners": 5,
          "yellowcards": 1,
          "redcards": 0,
          "throwins": 0,
          "freekicks": 0,
          "goalkicks": 0,
          "penalties": 0,
          "substitutions": 3,
          "ht_result": 1
        },
        "away": {
          "name": "Queretaro",
          "color": "",
          "position": "",
          "on_target": "",
          "off_target": "",
          "attacks": "",
          "dangerous_attacks": "",
          "possession": "",
          "goals": 0,
          "corners": 8,
          "yellowcards": 3,
          "redcards": 1,
          "throwins": 0,
          "freekicks": 0,
          "goalkicks": 0,
          "penalties": 0,
          "substitutions": 3,
          "ht_result": 0
        }
      },
      "odds": []
    }}

1 个答案:

答案 0 :(得分:3)

您可以对此类数据使用匿名类型deserialization。希望它有效。

//using Newtonsoft.Json;
var jsonData = JsonConvert.DeserializeAnonymousType(
    data,
    new 
    {
      events = new[]
      {
        new
        { 
          Id = new { info = "", stats = "", away = "", odds = "" }
        }
      }
  );            

foreach(var item in jsonData.events)
{
    var id=item.info.id; // getting id present in info
}
相关问题