>我有一个包装列表,看起来像这样:
[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"时出错 "测试.序列化测试+客户"。
将"类型名称处理"设置为"全部",我得到这个:
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 很好地使用包装列表吗?
我想你需要实现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);
}
}
尝试以下两种方法之一:
在列表周围创建一个名为 OrderCollection 的包装器集合类:
[Serializable]/[DataContract]
public OrderCollection : List<Order> { ... }
或者尝试将 LIST 转换为 ARRAY。
让我们知道任何一个是如何工作的。
我不确定序列化是否适用于 IEnumerable,您可以尝试使用 List 吗?
[Serializable]
public class OrderManager : List<Order>