Bernardo F. Coelho
Bernardo F. Coelho

Reputation: 55

.NET Core: Remove empty array from Json response

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.

Upvotes: 2

Views: 3040

Answers (1)

Daniel Beckmann
Daniel Beckmann

Reputation: 286

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);
}

Upvotes: 2

Related Questions