【发布时间】: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#