c# - 要序列化的同名属性

标签 c# .net json.net

我有一组想要序列化的对象。 在一个特定的类中,我有两个属性,并且我知道其中之一总是为空。因此,我想用相同的名称序列化此属性并忽略为空的属性。 下一个代码是一个示例。在本例中,Data 为 null,Data1 不为 null,但在实际情况中,问题的条件将决定哪一个为 null。

public class DataToSerialize 
{     
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public TData Data { get; set; }

    [JsonProperty("Data", NullValueHandling = NullValueHandling.Ignore)]
    public TData1 Data1 { get; set; }

    public DataToSerialize()
    {
        Data = null;
        Data1 = new TData1();
    }

 }

当我尝试序列化对象时,会引发下一个异常:

Newtonsoft.Json.JsonSerializationException: 'A member with the name 'Data' already exists on 'DataToSerialize'. Use the JsonPropertyAttribute to specify another name.'

最佳答案

最简单的选择可能是使用 [JsonIgnore] 属性来装饰两者,然后使用一个单独的属性来提供非空值:

public class DataToSerialize 
{     
    [JsonIgnore]
    public TData Data { get; set; }

    [JsonIgnore]
    public TData1 Data1 { get; set; }

    [JsonProperty("data")]
    public object SerializableData
    {
        get { return Data1 == null ? (object)Data : Data1; }
    }
 }

或者,如果它适合您的用例,只需使用通用类:

public class DataToSerialize<TData>
{     
    public TData Data { get; set; }
}

关于c# - 要序列化的同名属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767877/

相关文章:

c# - 在 C# 中有大量数字的斐波那契数列

.net - 为 Azure Function App 启用 VNet 集成时出现 "Http2ConnectionException: HTTP/2 error code ' PROTOCOL_ERROR ' (0x1)"错误

c# - 创建自定义 NewtonSoft JSON 转换器

c# - 解析未知 JSON 对象以获取特定值

json.net - Json转换继承字典的对象

c# - 不能明确指定标识列,但也不能不指定

c# - 使几个类似的特定方法通用

c# - 阻止 visual studio 2013 在新行上重新定位大括号?

c# - 如何在 C# 中安全地存储加密 key

c# - 快速高效地下载多个文件(异步)