使用JSON.NET - 我试图序列化可以包含任何其他对象的大量对象集合,这些对象可以包含任意数量的其他对象数组。在执行序列化和反序列化时,数据未正确键入/被销毁。稍后的搜索时间无法解决。
public class SubClass
{
public string theString;
}
public class MasterClass
{
public object theObj;
}
示例代码:
SubClass thesubclass = new SubClass(); thesubclass.theString = "TESTSTRING";
MasterClass theMaster = new MasterClass();
theMaster.theObj = thesubclass;
string jsonOut = JsonConvert.SerializeObject(theMaster, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All});
textBox1.Text = jsonOut;
//Out1: {"$type":"WindowsFormsApplication1.MasterClass, WindowsFormsApplication1","theObj":{"$type":"WindowsFormsApplication1.SubClass, WindowsFormsApplication1","theString":"TESTSTRING"}}
MasterClass testMaster = JsonConvert.DeserializeObject<MasterClass>(jsonOut);
string jsonOut2 = JsonConvert.SerializeObject(testMaster, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All});
textBox2.Text = jsonOut2;
//Out2: {"$type":"WindowsFormsApplication1.MasterClass, WindowsFormsApplication1","theObj":{"theString":"TESTSTRING"}}
基本上,经过主要对象的任何对象都会丢失它的类型。 // Out2应匹配// Out1,但它们永远不会。帮助
答案 0 :(得分:0)
您需要在反序列化时设置TypeNameHandling
设置:
MasterClass testMaster = JsonConvert.DeserializeObject<MasterClass>(jsonOut, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });