The API I have to work with returns an object when there would be only one entry in the array, a proper array otherwise. Here's an example:
Only one entry:
{
"product": {
"offers": {
"id": 1,
"price": 55.6
}
}
}
More than one entry:
{
"product": {
"offers": [
{
"id": 1,
"price": 55.6
},
{
"id": 2,
"price": 34.6
},
]
}
}
Is there some way to write code that deserializes both of those variants into arrays without writing a full JsonConverter
for the whole (deeply nested) response? Besides this weird seeming design decision, JSON.net can easily deserialize it, so I'm wondering if there is JSON.net feature that allows me to write something like this:
if (hasExpectedArray && hasEncounteredObject) {
deserialized.property = new List<T>();
deserialized.property.Add(objectEncountered);
}
My other idea would be to preparse the JSON and using some search and replace functionality to change all objects that can be arrays to arrays. But that seems dirty and brittle.
edit: actually forgot about the third case: it can also be a string or one of the array members can be a string:
{
"product": {
"offers": "This is an offer"
}
}
{
"product": {
"offers": [
{
"id": 1,
"price": 55.6
},
"This is another offer"
]
}
}