So for instance I have several types of cars that are being serialized to a .car file (this is a school project). I have three different types, ford, lexus, and dodge. I can save them fine. But with the current architecture of my program, when I deserialize I need to know the type before deserializing. For instance I am serializing like this:
if (CurrentCar.GetType() == typeof(Ford))
{
var JSON_CAR = JsonSerializer.Serialize((Ford)CurrentCar);
writer.Write(JSON_CAR);
}
When I deserialize, I need to know the type, before deserializing:
CurrentCar = JsonSerializer.Deserialize<???>(reader.ReadString());
How can I achieve this? Thank you.
CodePudding user response:
If you don't know the exact type of the car, your Json should contain property hold its type
{
"CarManufacturer" : "FORD"
}
you can add this property manually to your class
enum CarManufacturer
{
FORD,
BMW
}
class Car
{
[JsonConverter(typeof(JsonStringEnumConverter))]
public CarManufacturer Manufacturer { get; set; }
public string Name { get; set; }
}
class Ford:Car
{
public Ford()
{
Manufacturer = CarManufacturer.FORD;
}
public string OnlyFord { get; set; }
}
class BMW :Car
{
public BMW()
{
Manufacturer = CarManufacturer.BMW; ;
}
public string OnlyBMW { get; set; }
}
and you can serialize it as following
Car CurrentCar = new Ford { Name = "Foard Car", OnlyFord = "spacific feature in Ford Cars" };
string json = JsonSerializer.Serialize(CurrentCar, CurrentCar.GetType());
Console.WriteLine(json);
to Deserialize
Car Tempcar = JsonSerializer.Deserialize<Car>(json);
var Car = Tempcar.Manufacturer switch
{
CarManufacturer.BMW => JsonSerializer.Deserialize<BMW>(json),
CarManufacturer.FORD => JsonSerializer.Deserialize<Ford>(json),
_ => Tempcar
};
This should solve your problem, but it has some disadvantages
- You will make deserialization two times for same object !
- Adding some property to your models to work as Type Discriminator
- This solution will not work if your base class is an abstract class
to overcome this problem, you should write Custom converter Support polymorphic deserialization this will automatically add Type Discriminator to the generated json without adding any value to your Class
CodePudding user response:
Something like this?
public T GetObjectDeserialized<T>(string mydata) {
return JsonSerializer.Serialize<T>(mydata);
}
and then:
CurrentCar mycar = GetObjectDeserialized<CurrentCar.GetType()>(reader.ReadString());