0

I'm calling an API to fetch a list of devices. In my model i have an attribute for list of devices:

public List<Device> device { get; set; }

But, if the API returns 1 device, it's returned as just a Device, not a list of devices with 1 device.

Is there any good way to have a dynamic deserialize? I don't want to have two different models, and parse the JSON programatically just to know which object to deserialize as.

JsonConvert.DeserializeObject<ListDevicesByLabelModel>(responseText);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Lord Vermillion
  • 5,264
  • 20
  • 69
  • 109
  • can you provide more of your code. it could be something else that is going on. – Qpirate Feb 02 '15 at 09:04
  • Where's the offending Json? If the API returns a single object instead of an array with one object ... – Panagiotis Kanavos Feb 02 '15 at 09:05
  • It's nestled, the device list is an attribute of an attribute etc.. – Lord Vermillion Feb 02 '15 at 09:07
  • possible duplicate of [How to handle both a single item and an array for the same property using JSON.net](http://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n) – dbc Feb 02 '15 at 10:09
  • Try using `SingleOrArrayConverter` from here: https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n – dbc Feb 02 '15 at 10:09

1 Answers1

2

The dynamic keyword is still great for deserializing JSON, I would recommend that you take a look on this question.

Deserialize JSON into C# dynamic object?

dynamic data = Json.Decode(responseText);

And then you've got a dynamic object to work with instead of needing 2 models.

Otherwise you could also have just one item in the List.

Community
  • 1
  • 1
Thomas Lindvall
  • 599
  • 6
  • 13