c# - 序列化不同类的对象列表(实现通用接口(interface))仅呈现接口(interface)属性(如 IActionResult)

标签 c# system.text.json jsonserializer jsonconverter

我写了一个 Controller Action,它需要返回一个带有运动列表的 Json。这个 Json 数组只需要包含公共(public)属性(在接口(interface)级别定义)。

接口(interface)定义是:

public Interface ISport
{
    string TeamName {get; set;}
}

实现类是:

public Class SoccerTeam : ISport
{
   string TeamName {get; set;}
   int YellowCardsPerGame {get; set;}
}
public Class BasketTeam : ISport
{
   string TeamName {get; set;}
   int ThreePointsPerGame {get; set;}
}

如果我使用 System.Text.Json JsonSerialier 类及其 Serialize 方法将接口(interface)类 (ISport) 作为参数传递,我得到我需要的东西:

IEnumerable<ISport> sportscollection = Repository.GetAllSports();    
string Json = JsonSerialier.Serialize<ISport>(sportscollection);

返回

[{"TeamName":"ChicagBuls"},{"TeamName":"Chelsea"}]

但我不知道如何将此字符串转换为 IActionResult 以作为 Json 对象到达浏览器的方式。如果我尝试:

return Ok(json);

return Json(json);

浏览器得到有效响应,但内容是字符串,不是Json结构。

如果我使用 NetCore Controller Json 方法,IActionResult 会获取我正在寻找的 Json 对象,但此对象的内容包括所有类属性、来自接口(interface)的属性和类特定的属性。也就是说,如果我调用电话:

IActionResult Json = Json(sportscollection);

我得到:

[{"TeamName":"ChicagBuls","ThreePointsPerGame ":25},{"TeamName":"Chelsea","YellowCardsPerGame ":3}]

有什么方法可以让 Controller Json 方法在序列化时使用 ISport 类型? 有没有一种简单干净的方法可以将 Json String 正确的信息用于 IActionResult?

最佳答案

我得到了答案。

我只需要使用 Controller 方法 Content 返回 Json 字符串并将内容类型指定为“application/json”:

return Content(sportscollection, "application/json");

关于c# - 序列化不同类的对象列表(实现通用接口(interface))仅呈现接口(interface)属性(如 IActionResult),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72827936/

相关文章:

c# - 如何获取非类型化 FaultException 的详细信息?

c# - c#中url参数值的正则表达式

json - 最小 API - 请求正文中的 JSON 无效

c# - 如何让 JsonNode.ToJsonString(...) 按字母顺序生成属性?

c# - 当 .net5+ 中的嵌套属性名称相同时,将匿名类型序列化为 JSON 时出现异常

c# - IEnumerable.GroupBy() 中使用的类型有什么要求?

c# - 如何离线存储密码

java - JSON 序列化在 java POJO 中给出 null

java - BaseDexClassLoader 中的 JSONSerializer.toJSON ClassNotFoundException