Reputation: 157
I have a following json: need to Deserialize in 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 (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. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '[0]', line 1, position 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
}]
Upvotes: 0
Views: 1227
Reputation: 773
If you still want to Serialize the with your JSON you can use like below The below one works for your JSON
JsonConvert.DeserializeObject<List<PointElement[]>>(testJson);
Upvotes: 2
Reputation: 1302
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:
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:
[
{
"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);
Upvotes: 0