0

I am working with an 3rd party API that returns JSON data. I then deserialize this into a C# class containing multiple objects.

The issue is that I sometimes receive an error explaining:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into (my object type)

and that:

JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array

So, I decorate the object with an [JsonArray] attribute

However, I then get an error message explaining:

Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into (my object type)

and that:

JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object

It seems that sometimes the API is returning a JSON Array object and sometimes not.

The question is therefore how I define/decorate my object or define the class to be flexible enough to handle either? Is this possible?

This is the data that generates the 'Cannot deserialize the current JSON array' error:

"account_id": "0",
"account": [],
...

Here's the data that generates the 'object' error (when I decorate it as [JsonArray]):

"account_id": "3776",
"account": {
"id": 3776,
"name": "VISA Debit APP",
...
},
...

Obviously I want to nicely deserialize this to a C# class so I can work with data in a structured type safe manner. I have no control over the structure of this data so I'm compelled to work with this issue.

Any insights would be greatly appreciated.

ChrisCurrie
  • 1,589
  • 6
  • 15
  • 36
  • You could write a custom JsonConverter and handle the data deserialization logic there – Jinish Mar 23 '17 at 09:04
  • Yes, I guess so. Being lazy I had hoped I could decorate the object with some kind of attribute that just accepted that data as a string or something that I could later deserialize... In truth I don't need to obtain the data within the 'account' object anyway... – ChrisCurrie Mar 23 '17 at 10:26
  • Coming to think of it, another way (may be a little simpler way) could be to extend the DefaultContractResolver and override the CreateProperties method on it. I think it returns a list of JsonProperty. you could create a new property after examining the current property and its type using little reflection – Jinish Mar 23 '17 at 10:45
  • And in case you dont really need the data in the account object then just mark it with JsonIgnore attribute – Jinish Mar 23 '17 at 10:46
  • Looks like a duplicate of [How to handle both a single item and an array for the same property using JSON.net](http://stackoverflow.com/q/18994685/3744182). – dbc Mar 24 '17 at 19:03

0 Answers0