Home > Enterprise >  Serialize a list of Objects of different Classes (implementing a common Interface) rendering only th
Serialize a list of Objects of different Classes (implementing a common Interface) rendering only th

Time:07-02

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?

CodePudding user response:

I got the answer.

I just need to return the Json String using the Controller method Content and specifying the content type as "application/json":

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

CodePudding user response:

first, if the Type of sportCollection was an array of Isport not children of it, after using json(sportCollection) you will see that you want so that you can use Cast<ISport>() right after getting them from the repository and send them.
second, you can use JsonIgnore attribute top of each property of the (child) class to ignore them at serialization

  • Related