我有一个看起来像这样的包装列表:
[Serializable]
public class OrderManager : IEnumerable<Order>
{
public OrderManager()
{ }
private List<Order> orders = new List<Order>();
public void AddOrder(Order order)
{
orders.Add(order);
}
public IEnumerator<Order> GetEnumerator()
{
return orders.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return orders.GetEnumerator();
}
}
我在这样的客户类中包含一个字段实例:
[Serializable]
public class Customer
{
public Customer()
{ }
private OrderManager _orders
= new OrderManager();
public OrderManager Orders
{
get { return _orders; }
set { _orders = value; }
}
}
我像这样创建 JSON.NET 序列化程序:
private JsonSerializer GetSerializer()
{
var serializer = new JsonSerializer();
// on or off the type name handling doesn't help
//serializer.TypeNameHandling = TypeNameHandling.All;
var contractResolver = new DefaultContractResolver(true);
contractResolver.IgnoreSerializableAttribute = false;
contractResolver.IgnoreSerializableInterface = false;
serializer.ContractResolver = contractResolver;
serializer.PreserveReferencesHandling = PreserveReferencesHandling.All;
serializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return serializer;
}
客户对象的序列化有效,但在反序列化期间出现错误:
在“Tests.SerializationTests+Customer”上将值设置为“_orders”时出错。
将 TypeNameHandling 设置为 All 我得到这个:
Type specified in JSON 'Tests.SerializationTests+Order[], Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with 'Tests.SerializationTests+OrderManager, Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Path '_orders.$type', line 1, position 232.
知道如何让 Json.NET 与包装列表一起玩吗?