使类具有两个不同的字段(具有不同的类型)但具有相同的PropertyName
的最佳方法是什么。
通常,只要其中一个字段具有值,另一个字段就是null
。我知道我可以创造
两个不同的类,每个类只有一个字段。有没有比创建两个不同的类更好的选择了?
这是我要完成的工作的一个示例:
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Foo
{
private Foo(int x, bool asAList = false)
{
if (asAList)
{
Baz = new List<int> { x };
}
else
{
Bar = x;
}
}
public static JObject Get(int x, bool asAList = false)
{
Foo foo = new Foo(x, asAList);
return JObject.FromObject(foo);
}
[JsonProperty(PropertyName = "qwerty", NullValueHandling = NullValueHandling.Ignore)]
public int? Bar { get; set; } = null;
[JsonProperty(PropertyName = "qwerty", NullValueHandling = NullValueHandling.Ignore)]
public List<int> Baz { get; set; } = null;
}
我希望能够做到这一点:
JObject a = Foo.Get(1);
JObject b = Foo.Get(2, true);
答案 0 :(得分:1)
您可能有一个私有JToken
JsonProperty
,该私有JToken
JArray
用于序列化/反序列化到两个面向公众的属性中的任何一个。在设置操作上,然后将根据JToken
类型确定是否为[JsonConstructor]
,然后根据该类型确定要设置的其他属性。在get操作上,它将使用不为null的属性并将其转换为MemberSerialization.OptIn
。为了反序列化,您需要可以使用[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class Foo
{
[JsonConstructor]
private Foo()
{ }
private Foo(int x, bool asAList = false)
{
if (asAList)
Baz = new List<int> { x };
else
Bar = x;
}
public static JObject Get(int x, bool asAList = false)
{
Foo foo = new Foo(x, asAList);
return JObject.FromObject(foo);
}
[JsonProperty(PropertyName = "qwerty", NullValueHandling = NullValueHandling.Ignore)]
private JToken Qwerty
{
get
{
return Bar.HasValue ? JToken.FromObject(Bar) : Baz != null ? JToken.FromObject(Baz) : null;
}
set
{
if (value != null && value.Type == JTokenType.Array)
Baz = value?.ToObject<List<int>>();
else
Bar = value?.ToObject<int?>();
}
}
public int? Bar { get; set; }
public List<int> Baz { get; set; }
}
的构造函数。由于您不想直接对其他属性进行序列化/反序列化,因此可以使用{{1}}来删除[JsonProperty]属性。
{{1}}