我有一个包装列表,如下所示:
[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;
}
客户对象的序列化有效,但在反序列化期间我收到错误:
将值设置为'_orders'时出错 'Tests.SerializationTests +顾客'。
将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与包装列表一起玩得很好吗?
答案 0 :(得分:1)
我猜您需要实施ICollection<Order>
public class OrderManager : IEnumerable<Order>,ICollection<Order>
-
[Serializable]
public class OrderManager : IEnumerable<Order>,ICollection<Order>
{
public OrderManager()
{ }
private List<Order> orders = new List<Order>();
public Order this[int i]
{
set { AddOrder(value); }
get { return orders[i]; }
}
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();
}
public void Add(Order item)
{
AddOrder(item);
}
public void Clear()
{
orders.Clear();
}
public bool Contains(Order item)
{
return orders.Contains(item);
}
public void CopyTo(Order[] array, int arrayIndex)
{
throw new NotImplementedException();
}
public int Count
{
get { return orders.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(Order item)
{
return orders.Remove(item);
}
}
答案 1 :(得分:0)
尝试以下两种方法之一:
在List周围创建一个名为OrderCollection的包装器集合类:
[Serializable]/[DataContract]
public OrderCollection : List<Order> { ... }
或尝试将LIST转换为ARRAY。
让我们知道其中一个是如何工作的。
答案 2 :(得分:0)
我不确定序列化是否可以与IEnumerable一起使用,你可以尝试使用List吗?
[Serializable]
public class OrderManager : List<Order>