I have a problem that I don't know how to solve.
I have an object Movimientos
, and after a call to an ApiRest, I get a list of them, which I deserialize as follows.
result = JsonConvert.DeserializeObject<List<Movimientos>>(contenido);
So far perfect, the problem is when my call to the Api returns only a Movimiento
, that the same deserialization line skips:
{"Cannot deserialize the current JSON object (eg {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[Moves]' because the type requires a JSON array (eg [ 1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) 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."}
How can I make it work with both a json containing a list and a single item?
I edit with more simplified data: An example json returned by the api is
string contenido = "{ \"NumeroOrden\":null,\"Operacion\":null}";
And the Movements class
public class Movimientos
{
public string NumeroOrden { get; set; }
public string Operacion { get; set; }
}
Edit: The Json I get must be immutable. What the api returns is not mine, it does not depend on me and therefore it cannot be modified .
Since you cannot modify the REST API (as you indicate in the comments), you must then control the code , to check if what the Web API returns is an Array or a simple Object.
You can do it in many ways , I indicate two:
1 - Through exceptions (Try/Catch)
2 - Checking if it is Array (Starts with '[' and ends with ']')
Of course, these are two indicative ways to do it (improveable), now it all depends on your application and your level of programming .
UPDATE:
According to your comment:
Indeed, it is not recommended to use Generic Exceptions for conditional control flows. But there are cases (like yours) in which bad programming that cannot be corrected (like the Web API you consume) requires unorthodox methods to solve the problem. Sometimes (and not always) the end justifies the means .
As I told you in my comment you can do the following:
Add the
try catch
inside thetry
you execute your code which validates if you have several elements in the Object nothing happens, it returns normal, but if only one element comes you will generate an error with this you validate inside thecatch
you are going to put the code with which you only deserialize a object.