C
C#2y ago
Indeed

❔ Serialize inheriting types as a parent type

Hi! I have this class to group all localization types
public class Location {
}
public class Location {
}
sample localization type
public class Address : Location {
public string CityName { get; }

public Address(string cityName) {
CityName = cityName;
}

public override string ToString() {
return CityName;
}
}
public class Address : Location {
public string CityName { get; }

public Address(string cityName) {
CityName = cityName;
}

public override string ToString() {
return CityName;
}
}
and when i try to serialize it
public class PersistentData {
public Location? Location { get; set; }
}
public class PersistentData {
public Location? Location { get; set; }
}
data.Location = new Address("Kraków");
string json = JsonSerializer.Serialize(data);
File.WriteAllText(storageFilePath, json);
data.Location = new Address("Kraków");
string json = JsonSerializer.Serialize(data);
File.WriteAllText(storageFilePath, json);
I get
{
"Location": {}
}
{
"Location": {}
}
5 Replies
Indeed
Indeed2y ago
I guess its due to Location not having any properties but how can i go around it
Hugh
Hugh2y ago
If you add this attribute on Location, you'll get what you want:
[JsonDerivedType(typeof(Address), "Address")]
public class Location {
}
[JsonDerivedType(typeof(Address), "Address")]
public class Location {
}
This will add "$type":"Address", which will be referenced when deserializing If you ever want to be able to serialize an Address (that is specifically typed as such) and then deserialize it as a Location, you'll have to add the same attribute to the Address class
Indeed
Indeed2y ago
Thank you! It was exactly what I needed. Interesting how it is done. I was able to apply it to all derived classes ❤️
Hugh
Hugh2y ago
👍
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.