I'm trying to deserialize a JSON file containing an array of objects into a list of objects using Json.Net. Each object can be composed later from other complex objects like Id
{
"companies": [
{
"id": "1",
"companyName": "A",
"Id": {
"patterns": ["\\d{6}"],
"length": "6",
"explanation": "Text"
}
},
{
"id": "2",
"companyName": "B",
"Id": {
"pattern": ["\\d{6}"],
"explanation": "Text"
}
},
]
}
I have already tried to implement the following code which is supposed to read the file and deserialize it into a list of objects of type User. But it throws the following error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[CodeWars.User]' 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.
using (StreamReader file = new StreamReader(@"Path to file"))
{
string json = file.ReadToEnd();
List<User> items = JsonConvert.DeserializeObject<List<User>>(json);
}
public class User
{
public int id { get; set; }
public string companyName { get; set; }
public Dictionary<string, Id> Id { get; set; }
}
public class Id
{
public string pattern { get; set; }
public string explanation { get; set; }
}