I 'm working with visual studio and c# and I'm beginner.... :-(
I want to deserialize this json response :
[
{
"id": 10076,
"nom": "00 Test Api Upload"
},
{
"id": 9730,
"nom": "2021 Vacances Sabran Gruissan",
"**childs**": [
{
"id": 9731,
"nom": "Gruissan"
},
{
"id": 9745,
"nom": "Sabran"
}
]
}
]
I Try to do this :
public class Child
{
public int id { get; set; }
public string nom { get; set; }
}
public class Root
{
public int id { get; set; }
public string nom { get; set; }
public IList<Child> childs { get; set; }
}
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(response.Content);
But it's not ok
I have this kind of error :
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'GpxToolZ.VisuGpx Root' 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 '', line 1, position 1.'
Someone can help me ?
Thanks.
CodePudding user response:
You have an array of objects, not just the one, so instead of Root try to use Root[] or try this code
var jD = JsonConvert.DeserializeObject<Data[]>(json);
classes
public partial class Data
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("nom")]
public string Nom { get; set; }
[JsonProperty("childs", NullValueHandling = NullValueHandling.Ignore)]
public Child[] Childs { get; set; }
}
public partial class Child
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("nom")]
public string Nom { get; set; }
}