我有一個包裹列表,看起來像這樣:JSON.NET無法反序列包裹收集
[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;
}
客戶對象的序列工作,但反序列化過程出現錯誤:
Error setting value to '_orders' on 'Tests.SerializationTests+Customer'.
隨着TypeNameHandling設置爲我得到這樣的:
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發揮好與包裹清單?
啊哈!這就說得通了!我想要添加自己的邏輯,並且只需在刪除內部返回false,因爲我不想支持刪除。完美的作品!謝謝! – mbursill