Home > Mobile >  How to exclude a null property from JSON result when not using Json.Net?
How to exclude a null property from JSON result when not using Json.Net?

Time:10-18

I'm developing an ASP.NET Core web API, without EntityFrameworkCore, that uses controller classes for implementing the HTTP actions, and that generally follows this pattern:

public class MyItem
{
    public string Prop1 { get; set; }
    public MyOtherItem? OtherItem { get; set; }
}

public IEnumerable<MyItem> GetMyItems()
{
    List<MyItem> myItems = new();

    // Fill in myItems with stuff where OtherItem is sometimes null

    return myItems;
}

public class MyController : ControllerBase
{
    [HttpPost]
    public Task<IEnumerable<MyItem>> FetchMyItems()
    {
        var myItems = GetMyItems();

        return Task.FromResult(myItems);
    }
}

On making the POST request to FetchMyItems in Postman, the response is a JSON string containing an array of MyItem objects like this:

[
    {
        "prop1": "a string",
        "otherItem": {
            "otherprop1": "a string",
            "otherprop2": 0
        }
    },
    {
        "prop1": "a string",
        "otherItem": null
    }
]

What I would like is for the OtherItem property to be excluded if it is null. I have looked at adding the [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] attribute to the class but that has no effect, probably because whatever process is happening in FromResult() is not using the JsonSerializer.

Is there a different property attribute I can use? Or do I have to alter my action to use JsonSerializer?

CodePudding user response:

You can add the ignore null property condition when adding the controller. This uses System.Text.Json and not Newtonsoft library.

For .NET 5 and above:

builder.Services.AddControllers()
    .AddJsonOptions(opt =>
    {
        opt.JsonSerializerOptions.DefaultIgnoreCondition = 
            JsonIgnoreCondition.WhenWritingNull;
    });

For .NET Core 3.1:

services.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });

CodePudding user response:

You can use like this:

string json = JsonConvert.SerializeObject(myItems, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
  • Related