我正在尝试反序列化具有未命名数组数组的JSON对象,并且遇到了一些问题。我正在测试的代码:
var json = "{ \"Triangles\": [[1337],[1338],[1339]]}";
var mesh = JsonConvert.DeserializeObject<Mesh>(json);
和感兴趣的类别:
public class Mesh
{
[JsonProperty]
public Triangle[] Triangles { get; set; }
}
public class Triangle
{
[JsonProperty]
public int[] Indices { get; set; }
}
运行代码并尝试使用Newtonsoft反序列化,我得到以下异常:
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.
将[JsonArray]添加到Triangle类中会导致以下异常:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Message=Cannot create and populate list type ConsoleApp1.Triangle. Path 'Triangles[0]',position 17.
我想念什么?
编辑:我显然忘记提及的重要一件事是,出于语义原因,我想将其反序列化为文章中列出的类。也就是说,尽管将三角形反序列化为List<List<int>>
或int[][]
是可行的,但我还是非常希望不这样做。