【问题标题】:c# - Ignore empty/null value and guid empty in WebApiConfigc# - 在 WebApiConfig 中忽略空/空值和 guid 为空
【发布时间】:2019-06-28 20:40:39
【问题描述】:

我有一个控制器,它在函数 GET 中返回一个 json。我想忽略\删除我发送给第三方的空的、null 值和我的 json 的空指南。

在我使用的 WebApiConfig 中: config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; 它适用于 null 值,但不适用于 empty\guid.empty 值。

所以我尝试添加 config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new EmptyToNullConverter());和 EmptyToNullConverter 类。将空值转换为 null 然后被其他命令删除,但它不起作用,因为它不转换值。

类 EmptyToNullConverter 是:

public class EmptyToNullConverter : JsonConverter
    {
        private JsonSerializer _stringSerializer = new JsonSerializer();

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            string value = _stringSerializer.Deserialize<string>(reader);

            if (string.IsNullOrEmpty(value) ||  value == Guid.Empty.ToString())
            {
                value = null;
            }

            return value;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            _stringSerializer.Serialize(writer, value);
        }

    }

我该怎么办?

非常感谢

【问题讨论】:

  • JSON 是从具体类转换而来的吗?您是否在 guid 上尝试过 [JsonProperty("property_name",DefaultValueHandling = DefaultValueHandling.Ignore)]?
  • 谢谢!我有很多财产,所以我在全球范围内搜索。我尝试 config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore };但它会忽略所有默认值(bool,null ecc),即使它们是真的!
  • 我以为这只是 guid 的问题?
  • 问题在于空字符串 ("") 和 guid.empty (00000000-0000-0000-0000-000000000000)。
  • 有没有办法从 DefaultValueHandling = DefaultValueHandling.Ignore 中排除布尔值并只考虑某种类型?

标签: c#


【解决方案1】:

如果对象类型是Guid,即使您正在序列化。它仍然不能为空,尝试在序列化级别覆盖可能会造成混淆,就好像接收者在响应模型中期望 Guid 一样。即使您在 JSON 响应中不发送任何内容,他们的代码仍可能会初始化一个空的 Guid。

您有什么理由不能使用可为空的 Guid?鉴于您是堆栈溢出的新手,我可能会粗鲁地假设您是编码新手,因此您可能不熟悉可空值类型。

int、float、GUID、DateTime 等值类型将始终具有默认值,但是您可以通过以问号后缀声明它们来强制它们为空。

例如

int x // == 0;
int? x // == null;
Guid g // == 00000000-0000-0000-0000-000000000000;
Guid? g // == null;

一个好的一般规则是,如果一个值类型本质上可以为空,则使其可空。那么你就不需要任何花哨的转换了。

【讨论】:

  • 非常感谢!我的 guid 不能为空(Guid?),因为在同样的情况下它们是强制性的,而且我使用类的遗传。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-27
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
相关资源
最近更新 更多