NOTE: I am using Microsoft's new
System.Text.Json
and notJson.NET
so make sure answers address this accordingly.
Consider these simple POCOs:
interface Vehicle {}
class Car : Vehicle {
string make { get; set; }
int numberOfDoors { get; set; }
}
class Bicycle : Vehicle {
int frontGears { get; set; }
int backGears { get; set; }
}
The car can be represented in JSON like this...
{
"make": "Smart",
"numberOfDoors": 2
}
and the bicycle can be represented like this...
{
"frontGears": 3,
"backGears": 6
}
Pretty straight forward. Now consider this JSON.
[
{
"Car": {
"make": "Smart",
"numberOfDoors": 2
}
},
{
"Car": {
"make": "Lexus",
"numberOfDoors": 4
}
},
{
"Bicycle" : {
"frontGears": 3,
"backGears": 6
}
}
]
This is an array of objects where the property name is the key to know which type the corresponding nested object refers to.
While I know how to write a custom converter that uses the UTF8JsonReader
to read the property names (e.g. 'Car' and 'Bicycle' and can write a switch statement accordingly, what I don't know is how to fall back to the default Car
and Bicycle
converters (i.e. the standard JSON converters) since I don't see any method on the reader to read in a specific typed object.
So how can you manually deserialize nested objects like this?
Here's a simplistic approach that I hope works for you.
You can use a dynamic variable
I noticed in the comments that you weren't keen to use NetwonSoft.Json, you could use this code:
dynamic car = Json.Decode(json);
The Json class comes from here
I figured it out. You simply pass your reader/writer down to another instance of the JsonSerializer and it handles it as if it were a native object.
Here's a complete example you can paste into something like RoslynPad and just run it.
Here's the implementation...
Here's the demo code...
Here's the supporting two-way lookup used above...