我有一個實現IEnumerable的集合類,我無法反序列化同一個序列化版本。我使用Json.net v 4.0.2.13623Json.net序列化實現IEnumerable的自定義集合<T>
這裏是我的集合類的simplier版本,說明我的問題
public class MyType
{
public int Number { get; private set; }
public MyType(int number)
{
this.Number = number;
}
}
public class MyTypes : IEnumerable<MyType>
{
private readonly Dictionary<int, MyType> c_index;
public MyTypes(IEnumerable<MyType> seed)
{
this.c_index = seed.ToDictionary(item => item.Number);
}
public IEnumerator<MyType> GetEnumerator()
{
return this.c_index.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public int CustomMethod()
{
return 1; // Just for illustration
}
}
當我序列化,我得到下面的JSON
[
{
"Number": 1
},
{
"Number": 2
}
]
但是當我嘗試反序列化時,我得到以下異常 System.Exception:無法創建並填充列表類型MyTypes
還有t使用裏德序列化的提示,但沒有成功
這些測試功能我用
public void RoundTrip()
{
var _myTypes1 = new MyTypes(new[] { new MyType(1), new MyType(2) });
var _jsonContent = JsonConvert.SerializeObject(_myTypes1, Formatting.Indented);
var _myTypes2 = JsonConvert.DeserializeObject<MyTypes>(_jsonContent);
}
public void RoundTripWithSettings()
{
var _myTypes1 = new MyTypes(new[] { new MyType(1), new MyType(2) });
var _serializationSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Arrays };
var _jsonContent = JsonConvert.SerializeObject(_myTypes1, Formatting.Indented, _serializationSettings);
var _myTypes2 = JsonConvert.DeserializeObject<MyTypes>(_jsonContent, _serializationSettings);
}
有沒有人管理連載自己的收藏對象呢?
在此先感謝
帕特
您應該序列化並反序列化爲具體集合,例如List而不是IEnumerable 。爲了對某些東西進行反序列化,它需要一個實現而不僅僅是一個接口。 –
Deleted
Chris,改變了子類ReadOnlyCollection與其他一些變化,但我可以知道反序列化集合 –
pmcgrath
其實你也可以使用IList。它會爲你創建一個列表。但是沒有爲IEnumerable 定義默認集合。 –
Mithon