skip to Main Content

newbie question: how do i make my JSON output ignore null values? I don’t want to necessarily set each individual property to ignore null (as in decorate each property with [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] ), and few different global methods I found and tried didn’t work.
I am using .Net 6 and Newtonsoft.Json

I have this method in my controller

[HttpPost]
public async Task<ResponseJson> Post([FromBody] RequestJson value)
{
    DataProcessor processor = new DataProcessor(value);
    return processor.GetResults();
}

This is what ResponseJson looks like (with some properties omitted for brevity).

public class ResponseJson
{
    [JsonProperty(PropertyName = "items")]
    public List<Item> Items { get; set; }
}   

public class Item
{
    [JsonProperty(PropertyName = "name")]
    public string name { get; set; }
    
    [JsonProperty(PropertyName = "colour")]
    public string colour { get; set; }
    
    [JsonProperty(PropertyName = "parameters")]
    public ItemParameters parameters { get; set; }
}

DataProcessor doesn’t set the colour (null), or doesn’t set ItemParameters at all for some of the Item. When looking at the response from calling this method, the JSON string looks like this:

{
    "items":
        [
            {
                "name":"abc",
                "colour": "blue",
                "parameters":{<a bunch of parameters>}
            },
            {
                "name":"def",
                "colour": null
                "parameters":null
            },
            {
                "name":"ghi",
                "colour": null,
                "parameters":null
            },
            {
                "name":"jkl",
                "colour": "red",
                "parameters":{<a bunch of parameters>}
            }
        ]
}   

I want the properties with null values to be ignored completely so that it looks like this:

{
    "items":
        [
            {
                "name":"abc",
                "colour": "blue",
                "parameters":{<a bunch of parameters>}
            },
            {
                "name":"def"
            },
            {
                "name":"ghi"
            },
            {
                "name":"jkl",
                "colour": "red",
                "parameters":{<a bunch of parameters>}
            }
        ]
}   

3

Answers


  1. did you try this way?

    services.AddControllersWithViews().AddNewtonsoftJson(o => {   o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;   });
    
    Login or Signup to reply.
  2. Add the below codes in the ConfigureServices method in Startup.cs file, and it will work

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

    Seems the JsonSerializerOptions.IgnoreNullValues field is obsolete now, so try the new approach as stated below:

    services.AddMvc()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
        });
    
    Login or Signup to reply.
  3. net core 6 web api, in program, add AddJsonOptions in your AddControllers

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddControllers().AddJsonOptions(options =>
    { 
       options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });
    

    in net core mvc

    services.AddControllersWithViews().AddJsonOptions(options =>
    {
     options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    });
    

    in minimal API create service

    builder.Services.Configure<JsonOptions>(options =>
    {
        // Set this to true to ignore null or default values
        options.SerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
    });
    

    example complete using minimal API

    using Microsoft.AspNetCore.Http.Json;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    builder.Services.Configure<JsonOptions>(options =>
    {
        // Set this to true to ignore null or default values
        options.SerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
    });
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    
    app.MapGet("/GetWeatherForecast", () => new Person { FirstName = "Gérald"});
    app.Run();
    
    public class Person
    {
        public string? FirstName { get; set; }
        public string? LastName { get; set; }
    }
    

    result without ignore null

    {
      "FirstName": "Gérald",
      "LastName": null
    }
    

    result ignore null

    {
      "firstName": "Gérald"
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search