2

I'm having a problem related with the Json response. Here's a example of the response:

public class ContentModel
{
    public int? Total { get; set; }
    public IEnumerable<ContentResultModel> Results { get; set; }
    public FullContentModel Result { get; set; } 
    public IEnumerable<PaginationModel> Pagination { get; set; }

    public IEnumerable<ContentCommentsModel> Comments { get; set; }
}

I don't want the pagination to come in the response, if its empty. For example, for when it's null, I use:

options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;

Is there anything similar, that could solve my problem? I already search, and almost everybody uses a regex expression, but I want to avoid that, and want to use something more straightforward and simple, if its possible.

Even if I say the pagination property is null, it always changes to empty. Thanks.

1 Answers1

2

You can easily extend your class definition with a ShouldSerialize method, to omit the Pagination property, when the list is empty. You can find more information in the Json.Net docs.

public class ContentModel
{
    public int? Total { get; set; }
    public IEnumerable<ContentResultModel> Results { get; set; }
    public FullContentModel Result { get; set; } 
    public IEnumerable<PaginationModel> Pagination { get; set; }

    public IEnumerable<ContentCommentsModel> Comments { get; set; }

    public bool ShouldSerializePagination()
    {
        // don't serialize the Pagination property, when the list is empty
        return Pagination != null && Pagination.Count() > 0;
    }
}

Example usage: You then can return an object of the type ContentModel in an ApiController and the pagination property won't be present in the JSON response, when the list is null or empty.

[HttpGet]
public ActionResult<ContentModel> Get()
{
    var model = new ContentModel
    {
        Total = 12
    };

    return Ok(model);
}
Daniel Beckmann
  • 286
  • 2
  • 8
  • Daniel that example is not working for me ... I check the docs, and the difference is that they use JsonConvert.SerializeObject, and I return Json(object). – Bernardo F. Coelho Sep 27 '18 at 14:40
  • Are you using ASP.NET WebAPI and you return a ContentModel from a ApiController? Or how is your handling done? – Daniel Beckmann Sep 28 '18 at 11:32
  • Im using .net core 2.1 web api, and i use like this: "return StatusCode(200, contentModel);" – Bernardo F. Coelho Oct 01 '18 at 09:56
  • Added an example. Also .net core 2.1. – Daniel Beckmann Oct 01 '18 at 10:57
  • It may be worth mentioning that there is an option that means you can separate out the concern for "should serialise" into it's own class, thereby maintain SoC. Here's an example: https://stackoverflow.com/questions/34903151/how-to-omit-empty-collections-when-serializing-with-json-net – Dan Rayson Oct 01 '18 at 11:02