I want to deserialize a JSON file into a List<Person>
and I want to intercept the instances of Person
that gets created (not the instance of List<Person>
but this might be helpful too) is it possible to do it by implementing a custom IJsonTypeInfoResolver
or deriving from DefaultJsonTypeInfoResolver
?
I've tried to derive from DefaultJsonTypeInfoResolver
and create a custom resolver by overriding GetTypeInfo
but I'm not sure how to get the created instances of Person
.
I've checked some of the properties and methods on JsonTypeInfo
through debugging but I couldn't really understand what I should do or how I should use the API and the documentation seems lacking for my specific case, unfortunately.
Here is an example:
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
TypeInfoResolver = new JsonPersonResolver()
};
options.Converters.Add(new JsonDateTimeConverter());
options.Converters.Add(new JsonDateOnlyConverter());
options.Converters.Add(new JsonColorConverter());
options.Converters.Add(new JsonDecimalConverter());
var people = await JsonSerializer.DeserializeAsync<List<Person>>(stream, options);
sealed record Person
{
public string FullName { get; set; }
public int Age { get; set; }
}
sealed class JsonCustomResolver : DefaultJsonTypeInfoResolver
{
public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
{
var info = base.GetTypeInfo(type, options);
// Do what?
return info;
}
}