【发布时间】:2020-08-19 00:08:45
【问题描述】:
我正在尝试编写一个返回对象列表的 .NET Core API。以下类用于发送响应:
class AnimalResponse {
public IAnimal Animal { get; set; }
}
有一个空接口:
interface IAnimal {
}
还有2个类实现了这个接口:
class Cat : IAnimal {
public string CatProperty { get; set; }
}
class Dog : IAnimal {
public string DogProperty { get; set; }
}
如您所见,AnimalResponse 类的Animal 属性可以包含Cat 或Dog 类对象。这就是我发送响应的方式:
var response = new AnimalResponse() {
Animal = new Cat() {
CatProperty = "Cat Property Value"
}
};
return JsonResult(response);
由于某种原因,CatProperty 在序列化后从 API 响应中丢失。 API 返回以下 json:{Animal:{}}。
那么,如何让它包含所有特定于类的属性?
注意:我使用的是Microsoft.AspNetCore.Mvc.JsonResult,不是 Newtonsoft.Json。
【问题讨论】:
-
你解决过这个问题吗?
-
不,看起来不可能实现这种行为。
标签: c# json asp.net-mvc .net-core