Lets say I have these classes:
// serialize this enum value as string
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]
enum AnimalType
{
Dog,
Cat
}
abstract class Animal
{
public abstract AnimalType AnimalType { get; }
}
class Dog : Animal
{
public override AnimalType AnimalType => AnimalType.Dog;
}
class Cat : Animal
{
public override AnimalType AnimalType => AnimalType.Cat;
}
class Person
{
public Animal Pet { get; set; }
}
Then I would be able to serialize a Person but I will not be able to deserialize it:
var person = new Person();
person.Pet = new Dog();
// this works. It outputs: {"Pet":{"AnimalType":"Dog"}}
var json = System.Text.Json.JsonSerializer.Serialize(person);
// this does not work! and it makes sense
var clone = System.Text.Json.JsonSerializer.Deserialize<Person>(json);
In order to make the previous code work I will have to create this class:
class AnimalConverter : System.Text.Json.Serialization.JsonConverter<Animal>
{
public override Animal? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
// I am assuming the animal is a dog
return System.Text.Json.JsonSerializer.Deserialize<Dog>(ref reader);
}
public override void Write(Utf8JsonWriter writer, Animal value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
and now this code will work:
var person = new Person();
person.Pet = new Dog();
// I am able to serialize
var json = System.Text.Json.JsonSerializer.Serialize(person);
JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new AnimalConverter());
// now this works but only if Person has a Dog
var clone = System.Text.Json.JsonSerializer.Deserialize<Person>(json, options);
As you can see this code only works when the person has a Dog as a pet.
- How can I make it smart so that it knows how to desrialize it? I have tried playing with
Utf8JsonReader reader
and I am not able to seek and change position. It seems that my only option is to parse the whole document manually.
It will be great if I could perform a peek operation just to see what kind of object it is and then deserialize it based on that
Edit
Question explained in a more simple way:
I have a asp.net web API where a user sends me the json object:
{"Pet":{"AnimalType":"Dog"}}
How can I deserialize that into the correct c# object?