dimanche 24 janvier 2021

Cannot deserialize int List

I have a scenario that should be really simple but it isnt!

I have a type that is determined at runtime

I want to call

JSonConvert.DeserialiseObject<List<type>>(json);

via Make Generic Method as I need to determine the type at runtime

var entityTypes = _dbContext.Model.GetEntityTypes();
foreach (var entityType in entityTypes)
{
    var requiredType = entityType.ClrType;
    var testMethod = typeof(JsonConvert).GetMethods().FirstOrDefault(
       x => x.Name.Equals("DeserializeObject", StringComparison.OrdinalIgnoreCase) &&
         x.IsGenericMethod && x.GetParameters().Length == 1)
         ?.MakeGenericMethod(requiredType);

    var filename = $"my json.json";
    var json = File.ReadAllText(filename);
    var actualData2 = testMethod?.Invoke(null, new object[] { json });
}

This works perfectly if my json is for a single object

However, this is not the case, my json is for a list obviously the code above wont work because it expects my json to be a single object

So I tried to change to

var requiredType = typeof(List<entityType.ClrType>);

and entityType cannot resolved

What am I doing wrong? Sorry but I find generics really frustrating!

My ideal option was to be able to take a list of objects and convert that into a list of the required type but I cant get that to work in a generic way either hence having to try this

Cheers

Paul





Aucun commentaire:

Enregistrer un commentaire