我有以下从外部方收到的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 类名 和attributes 字段名 的Team类。相反,我希望它被命名,TeamScore并且还希望_从字段名称中删除并提供适当的名称。
Attributes
attributes
Team
TeamScore
_
JsonConvert.DeserializeObject<RootObject>(jsonText);
我可以重命名Attributes为TeamScore,但是如果我更改了字段名(attributes在Team类中),它将无法正确地反序列化并提供给我null。我该如何克服呢?
null
Json.NET具有JsonPropertyAttribute允许您指定JSON属性名称的名称,因此您的代码应为:
JsonPropertyAttribute
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; } }
文档: 序列化属性