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

本文关键字:变量 存在 保存 json 属性 | 更新日期: 2023-09-27 17:56:20

我制作了一个使用 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"
}

然后,我将创建变量,这些变量一旦在响应文本中获取内容,将所有变量拆分为:

String caption = the caption of json so (Premier League 2014/15)
String league = PL
我不知道我是否

明确了这个想法,以及我制作的代码是否良好。我依靠我在 vb.net strong 方面的经验,现在我正在尝试迁移到 c# 以达到学习目的。

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

您可以轻松地将 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);