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

前端 未结 6 1855
无人共我
无人共我 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:20

    I solved it by writing this extension:

    public static class JsonSerializationExtensions
    {
        public static string ToJson(this IEnumerable enumerable, bool includeDerivedTypesProperties = true)
                where T : class
        {
            var jsonOptions = new JsonSerializerOptions()
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };
    
            if (includeDerivedTypeProperties)
            {
                var collection = enumerable.Select(e => e as object).ToList();
                return JsonSerializer.Serialize(collection, jsonOptions);
            }
            else
            {
                return JsonSerializer.Serialize(enumerable, jsonOptions);
            }
        }
    }
    
        

    提交回复
    热议问题