Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

c# - Cannot deserialize int List<type> where type is determined t runtime

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

question from:https://stackoverflow.com/questions/65874165/cannot-deserialize-int-listtype-where-type-is-determined-t-runtime

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This:

.MakeGenericMethod(requiredType)

change to:

.MakeGenericMethod(typeof(List<>).MakeGenericType(requiredType))

More readable as:

var listType = typeof(List<>).MakeGenericType(requiredType);

and then

...
.MakeGenericMethod(listType)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...