新手问题:如何使JSON输出忽略null
值?我不想把每个单独的属性都设置为忽略null
(就像用[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
装饰每个属性一样(,我发现并尝试过的几种不同的全局方法都不起作用。我正在使用.Net 6和Newtonsoft.Json
我在我的控制器中有这个方法
[HttpPost]
public async Task<ResponseJson> Post([FromBody] RequestJson value)
{
DataProcessor processor = new DataProcessor(value);
return processor.GetResults();
}
这就是ResponseJson
的样子(为了简洁起见,省略了一些属性(。
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
不设置colour
(null
(,或者对于一些Item
根本不设置ItemParameters
。当查看调用此方法的响应时,JSON字符串如下所示:
{
"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>}
}
]
}
我希望完全忽略具有null
值的属性,使其看起来像这样:
{
"items":
[
{
"name":"abc",
"colour": "blue",
"parameters":{<a bunch of parameters>}
},
{
"name":"def"
},
{
"name":"ghi"
},
{
"name":"jkl",
"colour": "red",
"parameters":{<a bunch of parameters>}
}
]
}
net core 6 web api,在程序中,在AddControllers
中添加AddJsonOptions
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
网芯mvc
services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
在最小API中创建服务
builder.Services.Configure<JsonOptions>(options =>
{
// Set this to true to ignore null or default values
options.SerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
});
使用最小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; }
}
无忽略空的结果
{
"FirstName": "Gérald",
"LastName": null
}
结果忽略空
{
"firstName": "Gérald"
}
你尝试过这种方式吗?
services.AddControllersWithViews().AddNewtonsoftJson(o => { o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; });
在Startup.cs
文件中的ConfigureServices
方法中添加以下代码,它将工作
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
JsonSerializerOptions.IgnoreNullValues
字段现在似乎已经过时了,所以请尝试如下所述的新方法:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
对于在DOTNET 7+中运行的Minimal API(可能也是6(,现在它就像Minimal API教程的配置JSON序列化选项部分所显示的那样简单。只需按照以下摘录使用Builder.Services.ConfigureHttpJsonOptions()
:
var builder = WebApplication.CreateBuilder(args);
builder.Services.ConfigureHttpJsonOptions(options => {
options.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
// set other desired options here...
options.SerializerOptions.WriteIndented = true;
options.SerializerOptions.IncludeFields = true;
});
var app = builder.Build();