in my .NET 5 application I deserialize data using the System.Text.Json functions. This works for the most part.
Except for one field in the received JSON document, which can contain a number array, a string array or a single string (without array).
I can handle the first two cases by defining the field in my target type as List<dynamic>
. But if the third case occurs, the standalone string, an exception is thrown.
How can I achieve that this third case is also handled without exception. I would prefer to get a single element in my list. Is this possible?
This are 3 possible values in JSON:
{
"range": [
0,
100
]
}
{
"range": [
"yes",
"no"
]
}
{
"range": "n/a"
}
2
Answers
You will need either to write custom converter or dive into dynamic deserialization for example with
JsonDocument
:Demo @sharplab.io
you can try this custom converter