.Net NewtonSoft Json将地图解列为不同的属性名称 [英] .Net NewtonSoft Json Deserialize map to a different property name
问题描述
我有以下从外部参与者收到的JSON字符串。
I have following JSON string which is received from an external party.
{
"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; }
}
问题是我不喜欢属性类字段名称,而我希望它被命名为TeamScore,并从字段名称中删除_,并给出正确的名称。
Question is that I dont like the "Attribute class" and the "attributes field name" in the Team class, instead I want it to be named as "TeamScore" and also to remove "_" from the field names and give proper names.
JsonConvert.DeserializeObject<RootObject>(jsonText);
我可以将Attribute类更改为TeamScore,但如果我更改了文件名(Team Class中的属性),它不会正确反序列化并给我null。我如何克服这个问题?
I can change the "Attribute" class to a "TeamScore", but if i change the filed name (attributes in the Team Class), it won't deserialize properly and gives me null. How can I overcome this?
提前感谢。
推荐答案
Json.NET JsonPropertyAttribute它允许你指定Json属性的名字,所以你的代码应该是:
Json.NET has a JsonPropertyAttribute which allows you to specify name of Json property, so your code should be:
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; }
}
文档: 序列化属性
Documentation: Serialization Attributes
这篇关于.Net NewtonSoft Json将地图解列为不同的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!