我在将一些JSON字符串反序列化为c#对象时遇到了一个问题。
让我们假设我有以下代码:
public class A
{
public string Name { get; set; }
}
public class B : A
{
public int Age { get; set; }
}
public class C
{
public ObservableCollection<A> As
{
get;
set;
}
}
和我序列化以下对象_c
:
C _c = new C();
_c.As.Add(new B() { Name = "Max", Age = 4 });
这个效果很好。
但是我不能反序列化创建的json字符串和创建B的实例,因为ObservableCollection
被声明为A
为泛型类型。有没有办法告诉牛顿软件。Json使用B
而不是A
?
似乎你解决了它,但你可以通过改变你的类C
约束来实现同样的事情,而不使用任何自定义JSON转换器。见下文:
public class C<T> where T : A
{
private ObservableCollection<T> _as = new ObservableCollection<T>();
public ObservableCollection<T> As
{
get { return _as; }
set { _as = value; }
}
}
然后像
那样反序列化var _c = new C<B>();
_c.As.Add(new B() { Name = "Max", Age = 4 });
var serialized = JsonConvert.SerializeObject(_c);
var deserialized = JsonConvert.DeserializeObject<C<B>>(serialized); // B
解决了编写自定义JsonConverter的问题:
public class BCJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var currentType = (existingValue as System.Collections.ObjectModel.ObservableCollection<A>);
currentType.Clear();
var des = serializer.Deserialize<IList<B>>(reader);
foreach (var toAdd in des)
{
currentType.Add(toAdd);
}
return currentType;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
和
public class C
{
public virtual ObservableCollection<A> As
{
get;
set;
}
}
public class D : C
{
[Newtonsoft.Json.JsonConverter(typeof(BCJsonConverter))]
public override ObservableCollection<A> As
{
get;
set;
}
}