I have a number of JSON files each of which contains a list different of different class objects.
I can work out the data I'm expecting from the file name and have a generic JSON file reader which returns the correct data but I can't figure out how to assign that to anything in the calling method that allows me to access the results as the actual type.
I'm currently using this line:
var k = ReadJson<dynamic>(filePath, typeof(List<>).MakeGenericType(new[] { type }));
OR
var k = ReadJson<Object>(filePath, typeof(List<>).MakeGenericType(new[] { type }));
but they're both giving me
Unable to cast object of type 'System.Collections.Generic.List`1[Abc.Shared.Models.Location]' to type 'System.Collections.Generic.List`1[System.Object]'.
Conjecture: Since I can't call ReadJson directly can I call the ReadJson via reflection specifying the type of the generic 'T'? I've not been able work out if that's possible.
(For completeness here's the generic method - I don't think the problem is here though)
public static List<T> ReadJson<T>(string filePath, Type t) where T : class, new()
{
List<T> regions = new List<T>();
using (StreamReader file = System.IO.File.OpenText(filePath))
{
JsonSerializer serializer = new JsonSerializer();
regions = (List<T>)serializer.Deserialize(file, t);
}
return regions;
}
Aucun commentaire:
Enregistrer un commentaire