I have a JSON that has the following form:
{
"type": "oneOfMyTypes",
"body": {
//object corresponding to the type, contains some key-value pairs"
}
}
The structure of the body object depends on the type. So, I want to read the type, check that it is one of my predefined types, switch on the type and parse the body into a different object depending on the type. Body objects can be very different and I do not want to make a "super body" object containing all possible attributes. I also want to use JSON and I do not want to use any binary formats.
Question:
How can this be achieved using System.Text.Json
or Utf8Json
?
So far I have found JsonDocument+JsonElement and Utf8JsonReader. After the type is known, I will know the appropriate class for the body so I would like to use a simple parsing technique for the body, for example using JsonSerializer.Deserialize.
Answered here: Is polymorphic deserialization possible in System.Text.Json?