繁体   English   中英

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

[英]Retrieve specific value from JSON in C#

我需要从下面的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": []
    }}

您可以对此类数据使用匿名类型反序列化 希望它有效。

//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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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