1

I'm working on an extension for https://github.com/13xforever/gvas-converter with the ability to parse UnrealEngine .sav files. (https://github.com/RagingLightning/gvas-converter/blob/master/GvasFormat/Gvas.cs)

I have three relevant classes:

public class Gvas: main class to be deserialized, has a field public List<UEProperty> Properties = new List<UEProperty>();

public abstract class UEProperty: base class for all possible Unreal Engine properties with a field string Type denoting which subclass the current one is

public class UEStringProperty : UEProperty: fully functional class extending UEProperty tailored to the String variant

When I deserialize the Gvas object lie this:

Gvas data = JsonConverter.DeserialiteObject<Gvas>(<json-string>);

the deserializer tries to instantiate the UEProperty class multiple times to populate the Properties list and fails, since the class is abstract.

How can I tell the deserializer to instantiate a subclass based on th value of Type (eg. instantiate UEStringProperty when Type == "StringProperty")?

1 Answers1

0

Instead of depending on the default behavior of JsonConverter.DeserializeObject(), you may have to use a Custom JsonSerializer and a custom SerializationBinder instead of the DefaultSerializationBinder to get more control over the deserialization.

JsonSerializer offers more control than JsonConverter. For full control, you can derive a class from it and override methods.

The reason you have to do this is because, basic JSON serialization doesn't have enough type fidelity to round-trip back to your custom types. JSON just has the basics such as objects, properties, arrays, strings, numbers etc.,

See this article for details.

https://www.danylkoweb.com/Blog/create-a-custom-json-serialization-binder-to-resolve-derived-types-ON

Article excerpt:

Serialization and deserialization of derived types is unfortunately not straightforward regardless of the serializer you use. A solution to resolve derived types correctly for JsonSerializer is to use TypeNameHandling and add a custom JSON serialization Binder that derives from the DefaultSerializationBinder to override the BindToName and BindToType.

vvg
  • 1,010
  • 7
  • 25