我有两种格式的 JSON,我想将它们反序列化为一个类.我知道我们不能将两个 [JsonProperty] 属性应用于一个属性.
I have two format of JSON which I want to Deserialize to one class.
I know we can't apply two [JsonProperty] attribute to one property.
您能建议我实现这一目标的方法吗?
Can you please suggest me a way to achieve this?
string json1 = @"
{
'field1': '123456789012345',
'specifications': {
'name1': 'HFE'
}
}";
string json2 = @"
{
'field1': '123456789012345',
'specifications': {
'name2': 'HFE'
}
}";
public class Specifications
{
[JsonProperty("name1")]
public string CodeModel { get; set; }
}
public class ClassToDeserialize
{
[JsonProperty("field1")]
public string Vin { get; set; }
[JsonProperty("specification")]
public Specifications Specifications { get; set; }
}
我希望 name1 和 name2 都反序列化为规范类的 name1 属性.
I want name1 and name2 both to be deserialize to name1 property of specification class.
一个不需要转换器的简单解决方案:只需向您的类添加第二个私有属性,用 [JsonProperty("name2")],并让它设置第一个属性:
A simple solution which does not require a converter: just add a second, private property to your class, mark it with [JsonProperty("name2")], and have it set the first property:
public class Specifications
{
[JsonProperty("name1")]
public string CodeModel { get; set; }
[JsonProperty("name2")]
private string CodeModel2 { set { CodeModel = value; } }
}
小提琴:https://dotnetfiddle.net/z3KJj5
这篇关于分配给单个属性的多个 JsonProperty 名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取 XML 时忽略空格Ignore whitespace while reading XML(读取 XML 时忽略空格)
带有检查空元素的 XML 到 LINQXML to LINQ with Checking Null Elements(带有检查空元素的 XML 到 LINQ)
在 C# 中读取带有未闭合标签的 XMLReading XML with unclosed tags in C#(在 C# 中读取带有未闭合标签的 XML)
在 C# 中使用 Html 敏捷性解析表格、单元格Parsing tables, cells with Html agility in C#(在 C# 中使用 Html 敏捷性解析表格、单元格)
使用 LINQ 从 xml 中删除元素delete element from xml using LINQ(使用 LINQ 从 xml 中删除元素)
解析格式错误的 XMLParse malformed XML(解析格式错误的 XML)