One of the JSON API that I am consuming returns response that varies its data structure depending upon how many results are returned from the query. I am consuming it from C# and using JSON.NET to deserialize the response.
Here is the JSON that is returned from the API
Multiple Result Response:
{
"response": {
"result": {
"Leads": {
"row": [
{
"no": "1",
...
...
...
Single Result Response:
{
"response": {
"result": {
"Leads": {
"row": {
"no": "1",
...
...
...
Note the difference at "row" node which is either is an array in case of multiple results and object in case of single result.
Here are classes that I use to deserialize this data
Classes:
public class ZohoLeadResponseRootJson
{
public ZohoLeadResponseJson Response { get; set; }
}
public class ZohoLeadResponseJson
{
public ZohoLeadResultJson Result { get; set; }
}
public class ZohoLeadResultJson
{
public ZohoDataMultiRowJson Leads { get; set; }
}
public class ZohoDataMultiRowJson
{
public List<ZohoDataRowJson> Row { get; set; }
}
public class ZohoDataRowJson
{
public int No { get; set; }
...
}
The "Multiple Result Response" is deserialized without any problem but when there is only one result in the response, because of the data structure change, the response can't be deserialized. I get an exception
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON
object (e.g. {"name":"value"}) into type
'System.Collections.Generic.List`1[MyNamespace.ZohoDataRowJson]'
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3])
or change the deserialized type so that it is a normal .NET type (e.g. not a
primitive type like integer, not a collection type like an array or List<T>)
that can be deserialized from a JSON object. JsonObjectAttribute can also be
added to the type to force it to deserialize from a JSON object.
Path 'response.result.Notes.row.no', line 1, position 44.
Is there a way to handle this in Json.Net with some attribute and hopefully without having to write a converter?