1

I am try to serialize the JSON with the JsonConvert library but i am getting error:

JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'APIConsume.Models.RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

The JSON which I am getting is:

[{"id":0,"name":"Alice","image":"alice.jpg","fromLocation":"New York","toLocation":"Beijing"},{"id":1,"name":"Bob","image":"bob.jpg","fromLocation":"New Jersey","toLocation":"Boston"},{"id":2,"name":"Joe","image":"joe.jpg","fromLocation":"London","toLocation":"Paris"}]

My code line giving error is:

RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(apiResponse);

The RootObject class is generated by http://json2csharp.com/:

public class RootObject
{
    public int id { get; set; }
    public string name { get; set; }
    public string image { get; set; }
    public string fromLocation { get; set; }
    public string toLocation { get; set; }
}

Please help?

Joe Clinton
  • 145
  • 1
  • 12

1 Answers1

1

Try this:

var rootObject = JsonConvert.DeserializeObject<List<RootObject>>(apiResponse);
Óscar Andreu
  • 1,630
  • 13
  • 32
  • Thank you, it worked. http://json2csharp.com/ always worked but this time it generated me wrong class. – Joe Clinton Sep 13 '18 at 11:26
  • 1
    It actually is the right class, but you have to be aware that *if* your source is an array of X, *then* you must deserialize into a `List` *or* `X[]` (both will work). json2csharp is just not forcing any choice on you. – Peter B Sep 13 '18 at 11:35