我有以下从外部方收到的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; }
}
问题是我不喜欢Team类中的“Attribute class”和“attributes field name” . 相反,我希望它被命名为“TeamScore”,并从字段名称中删除“_”并给出正确的名称 .
JsonConvert.DeserializeObject<RootObject>(jsonText);
我可以将“属性”类更改为“TeamScore”,但如果我更改了文件名(团队类中的属性),它将不会正确反序列化并使我为空 . 我怎么能克服这个?
4 回答
Json.NET有
JsonPropertyAttribute
,它允许您指定JSON属性的名称,因此您的代码应为:文件: Serialization Attributes
如果您想使用动态映射,并且不希望使用属性来混淆模型,这种方法对我有用
用法:
逻辑:
添加到Jacks解决方案 . 我需要使用JsonProperty和Serialize反序列化,同时忽略JsonProperty(反之亦然) . ReflectionHelper和Attribute Helper只是一个辅助类,它获取属性的属性或属性列表 . 我可以包括,如果有人真正关心 . 使用下面的示例,您可以序列化viewmodel并获取“Amount”,即使JsonProperty是“RecurringPrice” .
用法:
模型:
扩展Rentering.com's答案,在需要处理多种类型的完整图表的情况下,并且您正在寻找强类型解决方案,此类可以提供帮助,请参阅下面的用法(流畅) . 它可以作为黑名单或每种类型的白名单运行 . 类型不能同时存在(Gist - 也包含全局忽略列表) .
用法: