Derived type's properties missing in JSON response from ASP.NET Core API

前端 未结 6 1857
无人共我
无人共我 2021-02-13 02:51

The JSON response from my ASP.NET Core 3.1 API controller is missing properties. This happens when a property uses a derived type; any properties defined in the derived type but

6条回答
  •  广开言路
    2021-02-13 03:02

    The documentation shows how to serialize as the derived class when calling the serializer directly. The same technique can also be used in a custom converter that we then can tag our classes with.

    First, create a custom converter

    public class AsRuntimeTypeConverter : JsonConverter
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return JsonSerializer.Deserialize(ref reader, options);
        }
    
        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            JsonSerializer.Serialize(writer, value, value?.GetType() ?? typeof(object), options);
        }
    }
    

    Then mark the relevant classes to be used with the new converter

    [JsonConverter(typeof(AsRuntimeTypeConverter))]
    public class MyBaseClass
    {
       ...
    

    Alternately, the converter can be registered in startup.cs instead

    services
      .AddControllers(options =>
         .AddJsonOptions(options =>
                {
                    options.JsonSerializerOptions.Converters.Add(new AsRuntimeTypeConverter());
                }));
    

提交回复
热议问题