如何在一些c#变量中保存json属性

时间:2015-06-14 10:57:30

标签: c# .net json

我制作了一个使用football-data.org提供的API的代码,我设法下载了包含我希望收到的所有参数的json。除非在responseText中有内容,现在我想在一些变量中划分responseText的内容。

string requestUrl = "http://api.football-data.org/alpha/soccerseasons/?season=2014";
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
request.Method = "GET";
request.ContentType = "application/json";

string responseText;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
    responseText = responseStream.ReadToEnd();
} 

Console.WriteLine(responseText);

正如您所看到的,json的结构也在文档中显示如下:

Example response:

{
"_links": {
   "self": { "href": "http://api.football-data.org/alpha/soccerseasons/354" },
   "teams": { "href": "http://api.football-data.org/alpha/soccerseasons/teams" },
   "fixtures": { "href": "http://api.football-data.org/alpha/soccerseasons/fixtures" },
   "leagueTable": { "href": "http://api.football-data.org/alpha/soccerseasons/leagueTable" }
},
 "caption": "Premier League 2014/15",
 "league": "PL",
 "year": "2014",
 "numberOfTeams": 20,
 "numberOfGames": 380,
 "lastUpdated": "2014-12-21T10:47:43Z"
}

然后我会创建曾经在responseText中获取内容的变量,将所有内容拆分为:

String caption = the caption of json so (Premier League 2014/15)
String league = PL

我不知道我是否明确了这个想法,以及我制作的代码是否合适。我依靠我对vb.net强大的经验,现在我正在尝试迁移到c#用于学习。

1 个答案:

答案 0 :(得分:1)

您可以轻松地将JSON解析为对象。结构看起来像这样(使用json2csharp生成,我会稍微编辑一下,因为有一些重复的代码):

public class Self
{
    public string href { get; set; }
}

public class Teams
{
    public string href { get; set; }
}

public class Fixtures
{
    public string href { get; set; }
}

public class LeagueTable
{
    public string href { get; set; }
}

public class Links
{
    [JsonProperty("self")]
    public Self Self { get; set; }
    [JsonProperty("teams")]
    public Teams Teams { get; set; }
    [JsonProperty("fixtures")]
    public Fixtures Fixtures { get; set; }
    [JsonProperty("leagueTable")]
    public LeagueTable LeagueTable { get; set; }
}

public class RootObject
{
    [JsonProperty("_links")]
    public Links Links { get; set; }
    [JsonProperty("caption")]
    public string Caption { get; set; }
    [JsonProperty("League")]
    public string League { get; set; }
    [JsonProperty("Year")]
    public string Year { get; set; }
    [JsonProperty("numberOfTeams")]
    public int NumberOfTeams { get; set; }
    [JsonProperty("NumberOfGames")]
    public int NumberOfGames { get; set; }
    [JsonProperty("LastUpdated")]
    public string LastUpdated { get; set; }
}

然后在使用序列化框架(例如Json.NET)将内容作为字符串读取之后,将其解析为对象:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(responseText);
Console.WriteLine(obj.Caption);