多个JsonProperty名称分配给单个属性 [英] multiple JsonProperty Name assigned to single property

查看:885
本文介绍了多个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; }        
}

我希望将name1name2都反序列化为规范类的name1属性.

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

推荐答案

一个不需要转换器的简单解决方案:只需在您的类中添加第二个private属性,用[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名称分配给单个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆