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 名称


基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01