multiple JsonProperty Name assigned to single property(分配给单个属性的多个 JsonProperty 名称)
问题描述
我有两种格式的 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 名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:分配给单个属性的多个 JsonProperty 名称
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
