我有一个dotnet核心webapi,有时在返回字段中有空字符串。我不想返回这些以保存带宽。我使用了JsonIgnoreCondition.WhenWritingDefault,但端点仍然返回空字符串字段。
这就是课堂
public class Person
{
public int PersonId { get; set; }
[DefaultValue("")]
public string FirstName { get; set; } = "";
[DefaultValue("")]
public string MiddleName { get; set; } = "";
[DefaultValue("")]
public string LastName { get; set; } = "";
}
这里是终点
[HttpGet]
public string Get()
{
var people = new List<Person>();
people.Add(new Person() {PersonId = 1, FirstName = "Joe"});
people.Add(new Person() {PersonId = 2, MiddleName = "Fred"});
people.Add(new Person() {PersonId = 3, LastName = "Jim"});
return JsonSerializer.Serialize(people, new JsonSerializerOptions(){
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
});
}
这是我得到的
[
{
"PersonId": 1,
"FirstName": "Joe",
"MiddleName": "",
"LastName": ""
},
{
"PersonId": 2,
"FirstName": "",
"MiddleName": "Fred",
"LastName": ""
},
{
"PersonId": 3,
"FirstName": "",
"MiddleName": "",
"LastName": "Jim"
}
]
我期待着
[
{
"PersonId": 1,
"FirstName": "Joe"
},
{
"PersonId": 2,
"MiddleName": "Fred"
},
{
"PersonId": 3,
"LastName": "Jim"
}
]
1条答案
按热度按时间c0vxltue1#
添加
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
属性将解决此问题。它将忽略可能具有空字符串值的属性。修改模型,如下所示:
希望这对你有帮助