1

I have a Json array string:

data = "[[2, 3, 32],[6,19,7],[17,19,10]]";

I would like it to serialize it by Newtonsoft json. So I made a class:

    public class Root
{
    public List<List<int>> MyArray { get; set; }
}

But this code is giving me an error:

List<Root> deserialize = JsonConvert.DeserializeObject<List<Root>>(e.data);

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Root' 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.

What Im doing wrong?

Scoppex
  • 57
  • 4
  • 1
    You can't deserialize to a scalar object if your JSON represents an array. You must deserialize to a collection. So you should `JsonConvert.DeserializeObject>>(e.data)` instead of `JsonConvert.DeserializeObject(e.data)` – mason Mar 25 '21 at 14:03
  • Its not working. I change it to: var deserialize = JsonConvert.DeserializeObject>>(e.data); and im getting: Newtonsoft.Json.JsonSerializationException: Error converting value 2 to type 'System.Collections.Generic.List`1[System.Int32]'. Path '[0]', line 1, position 2. ---> System.ArgumentException: Could not cast or convert from System.Int64 to System.Collections.Generic.List`1[System.Int32]. at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable (System.Object value, System.Type initialType, System.Type targetType) [0x00062] in <97722d3abc9f4cf69f9e21e6770081b3> – Scoppex Mar 25 '21 at 14:23
  • 1
    [Works on my machine](https://dotnetfiddle.net/6WwoHx). Is your data actually different than what you've shown in the question, and thus your numbers are too big for an int? – mason Mar 25 '21 at 14:26
  • 1
    I lost one character in my string when I was testing. It works now perfectly! Thank you so much for your help mason! – Scoppex Mar 25 '21 at 14:35

0 Answers0