I'm working on a blazor application webassembly core hosted, and when I'm trying to get a collection of items from the server, I get the right number of items but they are all empty.
My models look like this :
public interface IPerson
{
string Name { get; set; }
}
public class Customer : IPerson
{
public decimal CreditLimit { get; set; }
}
public class Employee : IPerson
{
public string OfficeNumber { get; set; }
}
public class Model
{
public string Name { get; set; }
public float SomeParameters { get; set; }
public IPerson Person { get; set; }
}
And I implemented a converter with the TypeDiscriminator template : https://docs.microsoft.com/fr-fr/dotnet/standard/serialization/system-text-json-converters-how-to#support-polymorphic-deserialization
Using client side :
var options = new JsonSerializerOptions();
options.Converters.Add(new PersonConverterWithTypeDiscriminator());
return await httpClient.GetFromJsonAsync<IEnumerable<Model>>(baseAPIUri, options);
Using server side :
services.AddControllersWithViews()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new NullableStructSerializerFactory());
options.JsonSerializerOptions.Converters.Add(new PersonConverterWithTypeDiscriminator());
options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.JsonSerializerOptions.IgnoreReadOnlyProperties = true;
});
Everithings works well when the client send the model to the server to save it, with httpClient.PostAsJsonAsync(baseAPIUri, item, options);
But when the client asks for the collection, I enter in the write() method, and never in the read() method in the convertor.
I tried to retrive the items without the serializer options and if the parameter Person is null, the deserialization is correct.
EDIT : I copied the Http response content in a file, created a new project .Net core in a console and add the lines :
var options = new JsonSerializerOptions
{
IgnoreNullValues = true,
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
IgnoreReadOnlyProperties = true
};
options.Converters.Add(new NullableStructSerializerFactory());
options.Converters.Add(new PersonConverterWithTypeDiscriminator());
string json = File.ReadAllText("D:\\model.json");
var newModel = System.Text.Json.JsonSerializer.Deserialize<IEnumerable<Model>>(json, options);
And it worked out