JsonIgnoreCondition.WhenWritingDefault不适用于空字符串

fcipmucu  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(164)

我有一个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"
  }
]
c0vxltue

c0vxltue1#

添加[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]属性将解决此问题。它将忽略可能具有空字符串值的属性。
修改模型,如下所示:

public class Person
{
    public int PersonId { get; set; }
    
    [JsonPropertyName("FirstName")]
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public string FirstName { get; set; } = "";
    
    [JsonPropertyName("MiddleName")]
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public string MiddleName { get; set; } = "";
    
    [JsonPropertyName("LastName")]
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public string LastName { get; set; } = "";
}

希望这对你有帮助

相关问题