I am trying to deserialize a JSON object that has an array of unnamed arrays and am running into some problems. The code I am running to test:
var json = "{ \"Triangles\": [[1337],[1338],[1339]]}";
var mesh = JsonConvert.DeserializeObject<Mesh>(json);
and the classes of interest:
public class Mesh
{
[JsonProperty]
public Triangle[] Triangles { get; set; }
}
public class Triangle
{
[JsonProperty]
public int[] Indices { get; set; }
}
Running the code and trying to deserialize using Newtonsoft I get the following exception:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ConsoleApp1.Triangle' 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<T> 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.
Path 'triangles[0]', line 1, position 17.
Adding [JsonArray] to the Triangle class results in the following exception though:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot create and populate list type ConsoleApp1.Triangle. Path 'Triangles[0]', line 1, position 17.
What am I missing?
Edit: An important thing I obviously forgot to mention was that I would like to deserialize it into the classes listed in the post for semantic reasons. That is, although deserializing Triangles into List<List<int>>
or int[][]
would work I would very much prefer to not do so.
> Triangles { get; set; }`
– DavidG Nov 04 '19 at 10:06>` and select to the right class with a simple select or write a custom parser.
– Drag and Drop Nov 04 '19 at 10:06>` or `int[][]` would work I would very much prefer to not do so." - That _is_ how the data is offered from the Json though. The fact you don't like it doesn't change that. Any transformations you do on that data to pour it into your own classes are _post-processing steps_ unrelated to the deserialisation itself. By trying to make it part of the deserialisation you're just complicating things.
– Nyerguds Nov 04 '19 at 10:55