[英]Deserialize Array of arrays in C#
I have a following json: need to Deserialize in C#. 我有以下json:需要在C#中反序列化。
[
[{
"ElementName": "H1 ",
"lat": 51.394319720562514,
"lng": -109.99996662139893
}, {
"ElementName": "H1 ",
"lat": 51.394319720562514,
"lng": -109.99995589256287
}],
[{
"ElementName": "H2 ",
"lat": 51.394319720562514,
"lng": -109.99996662139893
}, {
"ElementName": "H2 ",
"lat": 51.394319720562514,
"lng": -109.99995589256287
}]
]
I have write the following code to desirialize it. 我编写了以下代码以对其进行反序列化。
public class PointElement
{
public string ElementName { get; set; }
public double lat { get; set; }
public double lng { get; set; }
}
var testPointList = JsonConvert.DeserializeObject<List<PointElement>>(testNewJson);
but console shows the error 但控制台显示错误
Controllers.PointElementRecord' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly. Controllers.PointElementRecord”,因为该类型需要JSON对象(例如{“ name”:“ value”})才能正确反序列化。 To fix this error either change the JSON to a JSON object (eg {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array. 要解决此错误,可以将JSON更改为JSON对象(例如{“ name”:“ value”}),也可以将反序列化类型更改为数组,或者将实现集合接口的类型(例如ICollection,IList)更改为List,例如List从JSON数组反序列化。 JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 还可以将JsonArrayAttribute添加到类型中,以强制其从JSON数组反序列化。 Path '[0]', line 1, position 2. 路径“ [0]”,第1行,位置2。
need solution how to deserialize this kind array string as this code runs fine for below array 需要解决方案如何反序列化这种数组字符串,因为此代码对于以下数组运行良好
[{
"ElementName": "H1 ",
"lat": 51.394319720562514,
"lng": -109.99996662139893
}, {
"ElementName": "H1 ",
"lat": 51.394319720562514,
"lng": -109.99995589256287
}]
如果您仍想使用JSON序列化,则可以使用如下所示的内容。下面的一种适用于JSON
JsonConvert.DeserializeObject<List<PointElement[]>>(testJson);
If you want to create a list of list PointElement as your json descible, then the json converter should convert from List> instead of List : 如果要创建列表PointElement的列表作为json JSON,则json转换器应从List>而不是List转换:
var testPointList = JsonConvert.DeserializeObject<List<List<PointElement>>>(testNewJson)
Or incase you want to create a single list of PointElement then your json need to brackets [] which has nested array: 或者,如果您要创建一个PointElement列表,那么您的json需要放在带有嵌套数组的[]中:
[
{
"ElementName": "H1 ",
"lat": 51.394319720562514,
"lng": -109.99996662139893
}, {
"ElementName": "H1 ",
"lat": 51.394319720562514,
"lng": -109.99995589256287
},
{
"ElementName": "H2 ",
"lat": 51.394319720562514,
"lng": -109.99996662139893
}, {
"ElementName": "H2 ",
"lat": 51.394319720562514,
"lng": -109.99995589256287
}
]
and then you can call 然后你可以打电话
var testPointList = JsonConvert.DeserializeObject<List<PointElement>>(testNewJson);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.