I am trying to deserialize a json string that is coming from a js code, the data holds the json string that I want to deserialize.
The coming string is:
{"metalRingID":"FB11111","birdData":[{"longitude":-3.0851070084624497,"latitude":51.02832183751735,"gridRef":"ST2426","date":"2020-01-05T00:00:00"},{"longitude":-2.233409881591797,"latitude":51.5276985168457,"gridRef":null,"date":"2020-01-02T00:00:00"},{"longitude":-2.3790299892425537,"latitude":51.4547004699707,"gridRef":null,"date":"2020-01-03T00:00:00"},{"longitude":-1.6884700059890747,"latitude":51.68299865722656,"gridRef":null,"date":"2020-01-05T00:00:00"}]}
This is the model to hold that data:
using System;
using Newtonsoft.Json;
namespace BirdProject.Model.ViewModel
{
public class birdDataSolutionVM
{
[JsonProperty("metalRingID")]
public string metalRingID;
[JsonProperty("birdData")]
public List<birdRecordVM> birdData;
}
}
This is the line that should do the job.
var birdRecords = JsonConvert.DeserializeObject<List<birdDataSolutionVM>>(data);
The error I am receiving is the next:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[BirdProject.Model.ViewModel.birdDataSolutionVM]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\nPath 'metalRingID', line 1, position 15.
CodePudding user response:
You should be deserializing into the type, not an array of the type. It's a single object containing an array, but the root json is not an array.
var birdRecords = JsonConvert.DeserializeObject<birdDataSolutionVM>(data);