我想使用json.net序列化jQuery UI窗口小部件的选项,例如jQuery手风琴。
在基于整数0定义一个活动选项卡,
布尔值(设置为false)将崩溃。
我正在考虑创建2个无效的.NET属性:
int? Active
bool? IsActive
如果活动不为null,则应将其序列化为具有属性名称活动的整数如果ISARTIVE不是null,则应序列化为具有相同名称活动的布尔值。.NET代码将确保只有其中一个不能无效。
但是,当我将[jsonproperty(" active")放在两个属性上时,它都无法使用...
当前方法的困难是,让这两个字段无法正常工作,因为您不能将它们标记为[JsonProperty("active")]
。我的第一个尝试是定义类,如下所示:
class Accordion
{
[JsonProperty("active")]
[JsonConverter(typeof(ActiveTabConverter))]
public int Active { get; set; }
[JsonProperty("active")]
[JsonConverter(typeof(ActiveTabConverter))]
public bool IsActive { get; set; }
}
导致例外的
(我认为您也得到了这个),因为我在两个属性上使用了[JsonProperty("active")]
。删除以下属性之一也不起作用:也不例外,但是从未删除该属性的字段。
有效的工作是:
class Accordion
{
[JsonProperty("active")]
[JsonConverter(typeof(ActiveTabConverter))]
public int Active { get; set; }
[JsonIgnore]
public bool IsActive
{
get
{
return this.Active > -1;
}
}
public Accordion()
{
this.Active = -1;
}
}
请注意,仍然有两个字段,但其中只有一个将被认可。IsActive
是辅助属性。我在这里遵循的约定是Active
值大于0表示打开的手风琴选项卡,而-1等于从JSON接收false
。
class ActiveTabConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int) || objectType == typeof(bool);
}
public override object ReadJson(JsonReader reader, Type objectType,
JsonSerializer serializer)
{
var value = JValue.ReadFrom(reader);
if (value.Type == JTokenType.Integer)
{
return serializer.Deserialize<int>(reader);
}
return -1;
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
int item = (int)value;
if (item == -1)
{
writer.WriteValue(false);
}
else
{
writer.WriteValue(item);
}
writer.Flush();
}
}
此类负责应对Active
值的序列化和序列化。
我使用以下内容代码序列化/值。请注意,JSON实际上来自JQuery手风琴。对于所讨论的一个属性来说,这是过度的,但我认为最好使用真实的数据。
string json1 = "{"disabled":false,"create":null,"active":2,"animate":300,"collapsible":false,"event":"click","header":"> li > :first-child,> :not(li):even","heightStyle":"auto","icons":{"activeHeader":"ui-icon-triangle-1-s","header":"ui-icon-triangle-1-e","headerSelected":"ui-icon-triangle-1-s"},"activate":null,"beforeActivate":null,"navigation":false,"autoHeight":true,"clearStyle":false,"fillSpace":false,"change":null,"changestart":null,"animated":"slide"}";
string json2 = "{"disabled":false,"create":null,"active":false,"animate":300,"collapsible":true,"event":"click","header":"> li > :first-child,> :not(li):even","heightStyle":"auto","icons":{"activeHeader":"ui-icon-triangle-1-s","header":"ui-icon-triangle-1-e","headerSelected":"ui-icon-triangle-1-s"},"activate":null,"beforeActivate":null,"navigation":false,"autoHeight":true,"clearStyle":false,"fillSpace":false,"change":null,"changestart":null,"animated":"slide"}";
Accordion accordion = JsonConvert.DeserializeObject<Accordion>(json1);
string serializedJson = JsonConvert.SerializeObject(accordion);
accordion = JsonConvert.DeserializeObject<Accordion>(json2);
serializedJson = JsonConvert.SerializeObject(accordion);