I wrote a Controller Action that needs to return a Json with a List of Sports. This Json Array only needs to contain the common properties (defined at the Interface level).
The Interface definition is:
public Interface ISport
{
string TeamName {get; set;}
}
And the Implementation Classes are:
public Class SoccerTeam : ISport
{
string TeamName {get; set;}
int YellowCardsPerGame {get; set;}
}
public Class BasketTeam : ISport
{
string TeamName {get; set;}
int ThreePointsPerGame {get; set;}
}
If I use the System.Text.Json JsonSerialier class with its Serialize method passing the Interface class (ISport) as a parameter, I get what I need:
IEnumerable<ISport> sportscollection = Repository.GetAllSports();
string Json = JsonSerialier.Serialize<ISport>(sportscollection);
returns
[{"TeamName":"ChicagBuls"},{"TeamName":"Chelsea"}]
But I don't know how to cast this string into IActionResult in such a way that arrives to the browser as a Json object. If I try:
return Ok(json);
or
return Json(json);
The browser gets a valid response, but the content is a string, not a Json structure.
If I use the NetCore Controller Json method, the IActionResult gets the Json object I'm looking for, but the content of this object includes all the Class Properties, the ones from the Interface and the ones specific to the class. That is, if I make the call:
IActionResult Json = Json(sportscollection);
I get:
[{"TeamName":"ChicagBuls","ThreePointsPerGame ":25},{"TeamName":"Chelsea","YellowCardsPerGame ":3}]
Is there any way I can tell Controller Json method to use ISport type when Serializing? Is there a easy and clean way to use the Json String right information into a IActionResult?