【问题标题】:Suppress properties with null value on ASP.NET Web API在 ASP.NET Web API 上抑制具有空值的属性
【发布时间】:2013-01-07 08:13:30
【问题描述】:

我创建了一个将由移动应用程序使用的 ASP.Net WEB API 项目。我需要响应 json 来省略 null 属性,而不是将它们返回为 property: null

我该怎么做?

【问题讨论】:

    标签: c# asp.net-web-api


    【解决方案1】:

    WebApiConfig

    config.Formatters.JsonFormatter.SerializerSettings = 
                     new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
    

    或者,如果你想要更多的控制,你可以替换整个格式化程序:

    var jsonformatter = new JsonMediaTypeFormatter
    {
        SerializerSettings =
        {
            NullValueHandling = NullValueHandling.Ignore
        }
    };
    
    config.Formatters.RemoveAt(0);
    config.Formatters.Insert(0, jsonformatter);
    

    【讨论】:

    • 可耻 config.Formatters.XmlFormatter 没有相同的属性...:/
    • 从 Json.NET 5 开始(不确定以前的版本),您也可以这样做:config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore - 这将更新空值处理而不重置任何其他 json 序列化设置(例如使用小写在属性的第一个字母上)
    • 是否有可能只为一个属性做到这一点?
    • NullValueHandling = NullValueHandling.Ignore 对我的结果不起作用
    • 如果更改应该基于每个属性发生,并且使用的是足够新的 Json.Net 版本,则可以在属性上使用此属性:[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    【解决方案2】:

    我最终使用 ASP.NET5 1.0.0-beta7 在 startup.cs 文件中得到了这段代码

    services.AddMvc().AddJsonOptions(options =>
    {
        options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    });
    

    【讨论】:

      【解决方案3】:

      对于 ASP.NET Core 3.0,Startup.cs 代码中的 ConfigureServices() 方法应包含:

      services.AddControllers()
          .AddJsonOptions(options =>
          {
              options.JsonSerializerOptions.IgnoreNullValues = true;
          });
      

      【讨论】:

      • 这是最好的选择,因为在 API(没有 MVC)上你没有实现 MVC。
      【解决方案4】:

      您还可以使用[DataContract][DataMember(EmitDefaultValue=false)] 属性

      【讨论】:

      • 这是涵盖 xml 和 json 响应的唯一答案。
      【解决方案5】:

      如果您使用 vnext,在 vnext web api 项目中,将此代码添加到 startup.cs 文件。

          public void ConfigureServices(IServiceCollection services)
          {
              services.AddMvc().Configure<MvcOptions>(options =>
              {
                  int position = options.OutputFormatters.FindIndex(f =>  f.Instance is JsonOutputFormatter);
      
                  var settings = new JsonSerializerSettings()
                  {
                      NullValueHandling = NullValueHandling.Ignore
                  };
      
                  var formatter = new JsonOutputFormatter();
                  formatter.SerializerSettings = settings;
      
                  options.OutputFormatters.Insert(position, formatter);
              });
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-27
        • 1970-01-01
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多