反序列化JSON数据并显示C#

时间:2017-04-24 14:44:09

标签: c# json deserialization

我正在尝试反序列化以下数据并使用C#显示它们:

{  
   "_links":{  
      "self":{  
         "href":"http://api.football-data.org/v1/competitions/426/teams"
      },
      "competition":{  
         "href":"http://api.football-data.org/v1/competitions/426"
      }
   },
   "count":"20",
   "teams":[  
      {  
         "_links":{  
            "self":{  
               "href":"http://api.football-data.org/v1/teams/322"
            },
            "fixtures":{  
               "href":"http://api.football-data.org/v1/teams/322/fixtures"
            },
            "players":{  
               "href":"http://api.football-data.org/v1/teams/322/players"
            }
         },
         "name":"Hull City FC",
         "code":"HUL",
         "shortName":"Hull",
         "squadMarketValue":"122,250,000 €",
         "crestUrl":"http://upload.wikimedia.org/wikipedia/de/a/a9/Hull_City_AFC.svg"
      },
      {  
         "_links":{  
            "self":{  
               "href":"http://api.football-data.org/v1/teams/338"
            },
            "fixtures":{  
               "href":"http://api.football-data.org/v1/teams/338/fixtures"
            },
            "players":{  
               "href":"http://api.football-data.org/v1/teams/338/players"
            }
         },
         "name":"Leicester City FC",
         "code":"LCFC",
         "shortName":"Foxes",
         "squadMarketValue":"205,300,000 €",
         "crestUrl":"http://upload.wikimedia.org/wikipedia/en/6/63/Leicester02.png"
      }
   ]
}

我已经生成了这些类:

public class Team
{
    public Links2 _links { get; set; }
    public string name { get; set; }
    public string code { get; set; }
    public string shortName { get; set; }
    public string squadMarketValue { get; set; }
    public string crestUrl { get; set; }
}

public class RootObject
{
    public Links _links { get; set; }
    public int count { get; set; }
    public List<Team> teams { get; set; }
}

然后我尝试解析并显示数据:

private void ParseAndDisplay(JsonValue json)
{
    dynamic jsonObj = JsonConvert.DeserializeObject(json);

    foreach (var obj in jsonObj.teams)
    {
        Console.Out.WriteLine(obj.name);
    }
}

然而,当进入foreach循环时似乎打破了。谁能告诉我我错过了什么或做错了什么?出现未处理的异常错误。

2 个答案:

答案 0 :(得分:1)

要从您的团队列表中提取团队名称,您必须查询列表。

location.reload(true)

答案 1 :(得分:0)

您的代码是正确的,除非您使用错误更新了问题。

好的,让我告诉你在.net中再做一次。您也可以使用Linq

  1. Newtonsoft.Json.Linq引用到您的项目中。
  2. 并添加以下代码

    dynamic jsonObj = JObject.Parse(your_JSON_string);
    
    foreach (var obj in jsonObj.teams)
    
    {
       Console.WriteLine(obj.name);
    }