I have 3 classes; they contain each other in the following manner:
TestClass1
- TestClass2
- TestClass3
- TestClass3
- TestClass2
- TestClass3
- TestClass3
What I'm trying to do is to serialize and then deserialize this class structure.
Here are the classes:
class TestClass1
{
public List<object> Data { get; set; }
}
class TestClass2
{
public string Data1 { get; internal set; }
public TestClass3 Data2 { get; internal set; }
}
public TestClass3(DateTime dateTime, string v1, string v2, int v3)
{
this.dateTime = dateTime;
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
}
The code that I'm running is here:
var data = new List<TestClass2>()
{
new TestClass2()
{
Data1 = "test1",
Data2 = new TestClass3(new DateTime(2021, 02, 05), "Test", "Test2", 1234)
},
new TestClass2()
{
Data1 = "test2",
Data2 = new TestClass3(new DateTime(2021, 02, 06), "Test", "Test3", 1234)
},
new TestClass2()
{
Data1 = "test1",
Data2 = new TestClass3(new DateTime(2021, 02, 07), "Test23", "Test2", 5545)
},
};
var dataStream = new TestClass1()
{
Data = data.Select(a => (object)a).ToList(),
};
var streamSerialized = JsonSerializer.Serialize(dataStream);
var objects = JsonSerializer.Deserialize<TestClass1>(streamSerialized);
There are two issues here
Firstly, the objects don't serialize properly streamSerialized
doesn't contain any data for TestClass2.Data2
. Secondly, when I deserialize, it doesn't correctly deserialize into the class structure - that is, if I do:
var class2 = (TestClass2)objects.Data.First();
I get this error:
System.InvalidCastException: 'Unable to cast object of type 'System.Text.Json.JsonElement' to type 'ConsoleApp1.TestClass2'