新手問題:如何讓我的 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),或者根本沒有設定ItemParameters某些Item. 查看呼叫此方法的回應時,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>}
}
]
}
uj5u.com熱心網友回復:
你試過這種方式嗎?
services.AddControllersWithViews().AddNewtonsoftJson(o => { o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; });
uj5u.com熱心網友回復:
ConfigureServices在檔案中的方法中添加以下代碼,Startup.cs它將起作用
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
似乎該JsonSerializerOptions.IgnoreNullValues欄位現在已過時,因此請嘗試如下所述的新方法:
services.AddMvc()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
uj5u.com熱心網友回復:
net core 6 web api,在程式中,添加AddJsonOptions你的AddControllers
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;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/454774.html
上一篇:我想格式化ac#字典的元素
