我有一组想要序列化的对象。 在一个特定的类中,我有两个属性,并且我知道其中之一总是为空。因此,我想用相同的名称序列化此属性并忽略为空的属性。 下一个代码是一个示例。在本例中,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/