我有一个JSON,例如,看起来像
{"historymatch":
{
"id":[1581402],
"mid":[166],
"aid":[5621],
"bid":[18548],
"date":["24/05/16"],
"liveA":[3],
"liveB":[1],
"redA":[0],
"redB":[0],
"bc":["3-0"],
"ng":[0],
"rq":["-1.5"],
"rql":[0],
"worl":[0],
"oworl":[0]},
"match":
{
"166":
{
"n":"INT CF",
"c":"5691D8"
}
},
"team":
{
"5621":"Melbourne Knights",
"18548":"Dandenong City SC"
},
"note":{}
}
如您所见,比赛和团队中有动态属性和字段。我试图在我的 c# 类中反映这一点
class History<T> where T : new()
{
public HistoryMatch<T> HistoryMatch { get; set; }
}
class HistoryMatch<T> where T: new()
{
[JsonProperty("id")]
public IList<long> MatchId { get; set; }
[JsonProperty("mid")]
public IList<long> LeagueId { get; set; }
[JsonProperty("aid")]
public IList<long> TeamAId { get; set; }
[JsonProperty("bid")]
public IList<long> TeamBId { get; set; }
[JsonProperty("date")]
public IList<string> MatchDate { get; set; }
[JsonProperty("liveA")]
public IList<long> TeamAScore { get; set; }
[JsonProperty("liveB")]
public IList<long> TeamBScore { get; set; }
[JsonProperty("redA")]
public IList<long> TeamARedCard { get; set; }
[JsonProperty("redB")]
public IList<long> TeamBRedCard { get; set; }
[JsonProperty("bc")]
public IList<string> HalfTimeScore { get; set; }
[JsonProperty("ng")]
public IList<long> Ng { get; set; }
[JsonProperty("rq")]
public IList<string> Rq { get; set; }
[JsonProperty("rql")]
public IList<long> Rql { get; set; }
[JsonProperty("worl")]
public IList<long> Worl { get; set; }
[JsonProperty("oworl")]
public List<long> Oworl { get; set; }
[JsonProperty("match")]
public Dictionary<string,T> Match { get; set; }
[JsonProperty("team")]
public Team Team { get; set; }
[JsonProperty("note")]
public Note Note { get; set; }
}
class Match
{
[JsonProperty("n")]
public string Name { get; set; }
[JsonProperty("c")]
public string Color { get; set; }
}
class Team
{
public Dictionary<string, string> Values { get; set; }
}
class Note
{
}
然后我按以下方式反序列化它
var obj = JsonConvert.DeserializeObject<History<Match>>(responseText);
它被反序列化而没有错误,但类HistoryMatch
的属性Match
和Team
之后会null
。我现在已经尝试了几次,但似乎我在这里错过了一些重要的东西。有人可以给我一个建议吗?
在你的
Json Team
中,Match
和 Notes
不是HistoryMatch
的一部分,而是History
的一部分。以这种方式定义您的History
类,我做到了,我已经反序列化了您的团队并匹配值。
class History<T> where T : new()
{
public HistoryMatch<T> HistoryMatch { get; set; }
[JsonProperty("match")]
public Dictionary<string, T> Match { get; set; }
[JsonProperty("team")]
public Dictionary<string, string> Team { get; set; }
[JsonProperty("note")]
public Note Note { get; set; }
}
而且您不会拒绝将Team
定义为单独的类,正如我在您的 json 中看到的那样,它只是一个Dictionary<string, string>