我有一个项目,目前正在使用 Json.Net 进行 Json 反序列化类,如下所示:
public class Foo {
public Guid FooGuid { get; set; }
public string Name { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar {
public Guid BarGuid { get; set; }
public string Description { get; set; }
}
到目前为止,它工作正常。
为了使迭代更简单,我使Foo
类实现IEnumerable<Bar>
如下:
public class Foo : IEnumerable<Bar> {
public Guid FooGuid { get; set; }
public string Name { get; set; }
public List<Bar> Bars { get; set; }
public IEnumerator<Bar> GetEnumerator()
{
return Bars.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class Bar {
public Guid BarGuid { get; set; }
public string Description { get; set; }
}
但随后它无法反序列化对象。该错误令人困惑,因为它说它无法反序列FooGuid
化字段,但删除IEnumerable
接口再次起作用。
在模拟器或设备中的 MonoTouch 和 MonoDroid 环境中,问题是相同的。
关于如何使它工作的任何线索?
添加了重现此问题的代码:
public static class Tests {
public static void SerializeAndDeserializeFoo() {
// Serialize and deserialize Foo class
var element = new Foo
{
FooGuid = Guid.NewGuid(),
Name = "Foo name",
Bars = new List<Bar> {
new Bar { BarGuid = Guid.NewGuid(), Description = "Bar description" },
new Bar { BarGuid = Guid.NewGuid(), Description = "Bar description" },
new Bar { BarGuid = Guid.NewGuid(), Description = "Bar description" }
}
};
var serializedObject = JsonConvert.SerializeObject(element);
Console.WriteLine("Serialized Foo element: {0}", serializedObject);
// Exception if Foo implements IEnumerable
var deserializedObject = JsonConvert.DeserializeObject<Foo>(serializedObject);
Console.WriteLine("Foo deserialization worked!");
}
public static void SerializeAndDeserializeEnumerableFoo() {
// Serialize and deserialize Foo class
var element = new EnumerableFoo
{
FooGuid = Guid.NewGuid(),
Name = "Foo name",
Bars = new List<Bar> {
new Bar { BarGuid = Guid.NewGuid(), Description = "Bar description" },
new Bar { BarGuid = Guid.NewGuid(), Description = "Bar description" },
new Bar { BarGuid = Guid.NewGuid(), Description = "Bar description" }
}
};
var serializedObject = JsonConvert.SerializeObject(element);
Console.WriteLine("Serialized EnumerableFoo element: {0}", serializedObject);
try {
// Exception if Foo implements IEnumerable
var deserializedObject = JsonConvert.DeserializeObject<EnumerableFoo>(serializedObject);
Console.WriteLine("EnumerableFoo deserialization worked!");
}
catch (Exception e){
Console.WriteLine("EnumerableFoo deserialization failed!");
throw;
}
}
}
public class EnumerableFoo : IEnumerable<Bar> {
public Guid FooGuid { get; set; }
public string Name { get; set; }
public List<Bar> Bars { get; set; }
public IEnumerator<Bar> GetEnumerator()
{
return Bars.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class Foo {
public Guid FooGuid { get; set; }
public string Name { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar {
public Guid BarGuid { get; set; }
public string Description { get; set; }
}
示例项目:https ://www.dropbox.com/s/27i58aiz71dylkw/IEnumerableJson.zip