You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ServiceStack.Text不支持JsonIgnore(WhenWritingNull)条件的问题

解决ServiceStack.Text序列化带条件JsonIgnore的ProblemDetails属性问题

问题背景

Microsoft.AspNetCore.Mvc.ProblemDetails类的属性(如Title)带有带条件的JsonIgnore特性:

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
[JsonPropertyOrder(-4)]
[JsonPropertyName("title")]
public string? Title { get; set; }

使用ServiceStack.Text序列化时,即使Title不为空也会被忽略,且直接用JsConfig.IgnoreAttributesNamed = ["JsonIgnore"]会导致IgnoreDataMember也失效。


解决方案:自定义元数据过滤规则

通过JsConfig.MetadataFilter实现精准控制:既识别JsonIgnore的条件逻辑,又保留IgnoreDataMember的生效。

JsConfig.MetadataFilter = (type, property) =>
{
    // 处理JsonIgnoreAttribute的条件逻辑
    var jsonIgnoreAttr = property.GetCustomAttribute<JsonIgnoreAttribute>();
    if (jsonIgnoreAttr != null)
    {
        bool shouldIgnore = jsonIgnoreAttr.Condition switch
        {
            JsonIgnoreCondition.Always => true,
            JsonIgnoreCondition.WhenWritingNull => false,
            JsonIgnoreCondition.WhenWritingDefault => property.PropertyType.IsValueType && Activator.CreateInstance(property.PropertyType)?.Equals(property.GetValue(null)) == true,
            _ => true
        };
        property.SetConfig(new PropertyConfig { Ignore = shouldIgnore });
    }

    // 保留IgnoreDataMemberAttribute的默认处理
    var ignoreDataMemberAttr = property.GetCustomAttribute<IgnoreDataMemberAttribute>();
    if (ignoreDataMemberAttr != null)
    {
        property.SetConfig(new PropertyConfig { Ignore = true });
    }
};

说明

  • 对JsonIgnoreCondition.WhenWritingNull:设置为不忽略属性,ServiceStack.Text序列化时会自动跳过null值,符合原特性的预期
  • 对JsonIgnoreCondition.Always:保持忽略属性的逻辑
  • 对IgnoreDataMemberAttribute:单独处理,确保其忽略属性的规则生效
  • 无需编写自定义序列化器,仅通过全局配置即可解决问题

内容的提问来源于stack exchange,提问作者odyth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:47:14