我有两种格式的 JSON,我想将它们反序列化为一个类。
我知道我们不能将两个 [JsonProperty]
属性应用于一个属性。
您能建议我实现这一目标的方法吗?
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
属性。
最佳答案
一个不需要转换器的简单解决方案:只需向您的类添加第二个私有(private)属性,用 [JsonProperty("name2")]
标记它,然后设置第一个属性:
public class Specifications
{
[JsonProperty("name1")]
public string CodeModel { get; set; }
[JsonProperty("name2")]
private string CodeModel2 { set { CodeModel = value; } }
}
fiddle :https://dotnetfiddle.net/z3KJj5
https://stackoverflow.com/questions/43714050/