我有以下从外部方收到的 JSON 字符串。
{
"team":[
{
"v1":"",
"attributes":{
"eighty_min_score":"",
"home_or_away":"home",
"score":"22",
"team_id":"500"
}
},
{
"v1":"",
"attributes":{
"eighty_min_score":"",
"home_or_away":"away",
"score":"30",
"team_id":"600"
}
}
]
}
我的映射类:
public class Attributes
{
public string eighty_min_score { get; set; }
public string home_or_away { get; set; }
public string score { get; set; }
public string team_id { get; set; }
}
public class Team
{
public string v1 { get; set; }
public Attributes attributes { get; set; }
}
public class RootObject
{
public List<Team> team { get; set; }
}
问题是我不喜欢 Attributes
class name 和 attributes
field names Team
类。相反,我希望将其命名为 TeamScore
并从字段名称中删除 _
并给出正确的名称。
JsonConvert.DeserializeObject<RootObject>(jsonText);
我可以将 Attributes
重命名为 TeamScore
,但如果我更改字段名称(Team
中的 attributes
class),它不会正确反序列化并给我 null
。我该如何克服这个问题?
最佳答案
Json.NET - Newtonsoft有一个 JsonPropertyAttribute
允许您指定 JSON 属性的名称,因此您的代码应该是:
public class TeamScore
{
[JsonProperty("eighty_min_score")]
public string EightyMinScore { get; set; }
[JsonProperty("home_or_away")]
public string HomeOrAway { get; set; }
[JsonProperty("score ")]
public string Score { get; set; }
[JsonProperty("team_id")]
public string TeamId { get; set; }
}
public class Team
{
public string v1 { get; set; }
[JsonProperty("attributes")]
public TeamScore TeamScores { get; set; }
}
public class RootObject
{
public List<Team> Team { get; set; }
}
关于json - .NET NewtonSoft JSON 反序列化映射到不同的属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15915503/