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

ServiceStack中是否有设置可在JSON序列化时保留空列表?

在ServiceStack JSON序列化中保留空列表的方法

ServiceStack的JSON序列化默认会忽略空集合(包括空List),不会把它们输出到JSON结果里。如果要保留空列表,有两种常用方法:

全局生效配置

在应用启动时设置全局序列化规则,让所有空集合都被序列化:

JsConfig.IncludeEmptyCollections = true;

设置后,所有类型的空集合(List、数组等)都会被序列化为[]而不是被省略。

局部生效配置(针对特定属性/类型)

如果不想全局修改,只想让特定属性或类型保留空列表,可以用.NET的DataContract和DataMember特性:

  1. 给DTO类加上[DataContract]特性
  2. 给需要保留空列表的属性加上[DataMember(EmitDefaultValue = true)]特性

示例代码:

[DataContract]
public class SampleDto
{
    // 这个空列表会被序列化
    [DataMember(EmitDefaultValue = true)]
    public List<int> EmptyNumbers { get; set; } = new List<int>();

    // 这个空列表会被默认忽略(没加特性)
    public List<string> IgnoredEmptyList { get; set; } = new List<string>();
}

另外,也可以单独针对某个类型配置序列化规则:

// 只让List<string>类型的空集合被序列化
JsConfig<List<string>>.IncludeEmptyCollections = true;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:10:20