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

查看:29
本文介绍了分配给单个属性的多个 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.

推荐答案

一个不需要转换器的简单解决方案:只需向您的类添加第二个私有属性,用 [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天全站免登陆