.NET NewtonSoft JSON反序列化到一个不同的属性名称映射
.NET NewtonSoft JSON反序列化到一个不同的属性名称映射
我收到了一个外部方发来的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 { get; set; } }
问题在于我不喜欢Attributes
类名和Team
类中的attributes
字段名。相反,我想将其命名为TeamScore
,并且去掉字段名中的_
并给它们适当的名称。
JsonConvert.DeserializeObject(jsonText);
我可以将Attributes
重命名为TeamScore
,但如果我改变字段名(在Team
类中的attributes
),它不会正确反序列化,会给我返回null
。我该如何克服这个问题呢?
admin 更改状态以发布 2023年5月23日
如果您想使用动态映射,并且不想在模型中混杂着属性,这个方法适用于我。
使用方法:
var settings = new JsonSerializerSettings(); settings.DateFormatString = "YYYY-MM-DD"; settings.ContractResolver = new CustomContractResolver(); this.DataContext = JsonConvert.DeserializeObject(jsonString, settings);
逻辑:
public class CustomContractResolver : DefaultContractResolver { private DictionaryPropertyMappings { get; set; } public CustomContractResolver() { this.PropertyMappings = new Dictionary { {"Meta", "meta"}, {"LastUpdated", "last_updated"}, {"Disclaimer", "disclaimer"}, {"License", "license"}, {"CountResults", "results"}, {"Term", "term"}, {"Count", "count"}, }; } protected override string ResolvePropertyName(string propertyName) { string resolvedName = null; var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName); return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName); } }
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 ListTeam { get; set; } }
文档:序列化属性