0

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?

1

2 Answers 2

4

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;
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Going into the Program.cs and altering the AddControllers to ignore nulls was the cleanest approach without me need to fundamentally alter my code. Thanks.
0

You can use like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.