34
我试图序列化/反序列化Dictionary<string, object>
这似乎工作正常,如果对象是一个简单的类型,但在对象更复杂时不起作用。序列化/反序列化JSON.NET的对象字典
我有这个类:
public class UrlStatus
{
public int Status { get; set; }
public string Url { get; set; }
}
在我的字典里我加List<UrlStatus>
与“重定向链”的关键和几个简单的字符串的钥匙“状态”,“地址”,“父代URL” 。我碰到JSON.Net后面的字符串看起来是这样的:
{"$type":"System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib","Status":"OK","Url":"http://www.ehow.com/m/how_5615409_create-pdfs-using-bean.html","Parent Url":"http://www.ehow.com/mobilearticle35.xml","Redirect Chain":[{"$type":"Demand.TestFramework.Core.Entities.UrlStatus, Demand.TestFramework.Core","Status":301,"Url":"http://www.ehow.com/how_5615409_create-pdfs-using-bean.html"}]}
的代码我使用序列化的样子:
JsonConvert.SerializeObject(collection, Formatting.None, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
});
反序列化我做:
JsonConvert.DeserializeObject<T>(collection, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,
});
字典恢复正常,所有字符串恢复正常,但列表没有得到正确的反序列化。它只是回来为
{[
{
"$type": "XYZ.TestFramework.Core.Entities.UrlStatus, XYZ.TestFramework.Core",
"Status": 301,
"Url": "/how_5615409_create-pdfs-using-bean.html"
}
]}
当然我可以再次deserailize这个字符串,我得到了正确的对象,但似乎JSON.Net应该这样做对我来说。很明显,我做错了什么,但我不知道它是什么。
我使用Json.NET 3.5版本8我甚至下载的zip再次得到肯定。 – 2010-09-19 06:18:04
刚刚尝试了最新的版本53965,仍然没有工作。 – 2010-09-19 06:27:43
TypeNameHandling = TypeNameHandling.All是诀窍。 – 2010-09-19 19:02:53