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);
5
  • can you provide more of your code. it could be something else that is going on. Commented Feb 2, 2015 at 9:04
  • Where's the offending Json? If the API returns a single object instead of an array with one object ... Commented Feb 2, 2015 at 9:05
  • It's nestled, the device list is an attribute of an attribute etc.. Commented Feb 2, 2015 at 9:07
  • possible duplicate of How to handle both a single item and an array for the same property using JSON.net Commented Feb 2, 2015 at 10:09
  • Try using SingleOrArrayConverter from here: stackoverflow.com/questions/18994685/… Commented Feb 2, 2015 at 10:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.