Reputation: 1309
I have the below classes:
public class Datum
{
public bool Prop1 { get; set; }
public bool Prop2 { get; set; }
public bool Prop3 { get; set; }
public bool Prop4 { get; set; }
public bool Prop5 { get; set; }
public bool Prop6 { get; set; }
}
public class Example
{
public IList<Datum> data { get; set; }
}
And I have the below json in variable:
var json = @"{'data': [
{
'Prop1': true,
'Prop2': true,
'Prop3': true,
'Prop4': true,
'Prop5': true,
'Prop6': true
},
{
'Prop1': true,
'Prop2': true,
'Prop3': true,
'Prop4': true,
'Prop5': true,
'Prop6': false
},
{
'Prop1': false,
'Prop2': true,
'Prop3': true,
'Prop4': true,
'Prop5': false,
'Prop6': false
},
{
'Prop1': false,
'Prop2': true,
'Prop3': true,
'Prop4': false,
'Prop5': false,
'Prop6': false
}]
}";
I am Using Netonsoft JSON.NET to deserialize the JSON into C# Objects like below:
var items = JsonConvert.DeserializeObject<List<Example>>(json);
But I am getting the below error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ReadJson.Example]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. To 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. Path 'data', line 1, position 8.'
I ran the exact same code in some online c# editor and this just works fine. But when I try in my local Visual Studio it gives the error. I am using Newtonsoft Version 12 and above.
Can anybody explain me what is wrong with my code.
Thanks in Advance.
Upvotes: 0
Views: 149
Reputation:
You don't have a list of Example
. You have an Example
, singular. Example
has a data
property; your JSON only contains one instance of that property, and its enclosing object isn't in an array.
So,
JsonConvert.DeserializeObject<Example>(json)
Upvotes: 7