将类序列化为对象

本文关键字:对象 序列化 | 更新日期: 2023-09-27 18:10:04

使用JSON。我正在尝试序列化一个可以包含任何其他对象的大量对象集合,这些对象可以包含任何数量的其他对象的数组。在执行序列化和反序列化时,数据输入不正确/被销毁。几个小时的搜索后,还是无法解决。

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"}}

基本上任何超过main对象的对象都在失去它的类型。//Out2应该匹配//Out1,但它们从不匹配。帮助

将类序列化为对象

反序列化时还需要设置TypeNameHandling设置:

MasterClass testMaster = JsonConvert.DeserializeObject<MasterClass>(jsonOut, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });