我有两种格式的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; }        
}

I want name1 and name2 both to be deserialize to name1 property of specification class.

推荐答案

一个不需要转换器的简单解决方案:只需向类中添加第二个私有属性,将其标记为[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

Json相关问答推荐

按照对象键的值对PostgreSQL JSONB对象进行排序'

如何在Power BI中集成API和JSON数据后将数据转换为表?

将PNG图像保存为Python中的JSON文件

VSCode 为 python 文件添加标尺,但不为 C 文件添加标尺.为什么?

Delphi 11.3无法从变体创建/添加JSON

颠簸转换问题

如何加入或合并列表元素列表(未知长度)

使用 SwiftUI 在 API 调用中解码嵌套 JSON 响应时遇到问题

Jolt - 在同一级别添加时组合值的问题

如何使用 gson 将数据保存在 json 文件中?

如何对使用转换器的 Grails 服务进行单元测试?

读取 HttpwebResponse json 响应,C#

在 JSON 对象中强制执行非空字段

Spring Security 和 JSON 身份验证

使用 ajax 将 JSON 发送到 PHP

JSON 模式 - 如果对象*不*包含特定属性则有效

Jersey 2.0 相当于 POJOMappingFeature

从调试器获取 IntelliJ Idea 中的 JSON 对象

按键值过滤 JSON

TypeError:使用Python解析JSON时字符串索引必须是整数?