我正在尝试反序列化一个 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]', line 1, position 17.
我错过了什么?
编辑:我显然忘记提到的一件重要的事情是,出于语义原因,我想将其反序列化为帖子中列出的类。也就是说,尽管将 Triangles 反序列化为List<List<int>>
或int[][]
会起作用,但我非常希望不这样做。