gpt4 book ai didi

c# - 如果 JSON.NET 中的值为 null 或空格,则阻止序列化

转载 作者:行者123 更新时间:2023-11-30 23:01:47 25 4
gpt4 key购买 nike

我有一个对象需要以不序列化 null 和“空白”(空或只是空格)值的方式进行序列化。我不控制对象本身,因此无法设置属性,但我知道所有属性都是字符串。将 NullValueHandling 设置为 Ignore 显然只会让我获得解决方案的一部分。

“似乎”(据我所知)我需要做的是创建自定义 DefaultContractResolver,但我还没有想出有效的解决方案。这里有几个失败的尝试,仅供引用,没有抛出异常但对序列化也没有明显影响:

public class NoNullWhiteSpaceResolver : DefaultContractResolver
{
public static readonly NoNullWhiteSpaceResolver Instance = new NoNullWhiteSpaceResolver();

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);

/* this doesn't work either
if (property.ValueProvider.GetValue(member) == null ||
(property.PropertyType == typeof(string) &&
string.IsNullOrWhiteSpace((string)property.ValueProvider.GetValue(member))))
{
property.ShouldSerialize = i => false;
}*/

if (property.PropertyType == typeof(string))
{
property.ShouldSerialize =
instance =>
{
try
{
string s = (string) instance;
bool shouldSkip = string.IsNullOrWhiteSpace(s);
return !string.IsNullOrWhiteSpace(s);
}
catch
{
return true;
}
};
}

return property;
}
}

我正在通过

实现解析器
string str = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
{
Formatting = Formatting.None;
ContractResolver = new NoNullWhiteSpaceResolver();
});

也许我会倒退,但我很欣赏人们的任何见解。我已经解决了这个问题,方法是使用扩展方法/反射来迭代对象的属性,如果它是“nullorwhitespace”,则将值设置为 null,然后使用标准的 NullValueHandling 但我希望我能找到一种方法来在序列化中配置所有这些。

最佳答案

这似乎可行:

public class NoNullWhiteSpaceResolver : DefaultContractResolver {
public static readonly NoNullWhiteSpaceResolver Instance = new NoNullWhiteSpaceResolver();

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) {
JsonProperty property = base.CreateProperty(member, memberSerialization);

if (property.PropertyType == typeof(string)) {
property.ShouldSerialize =
instance => {
try {
var rawValue = property.ValueProvider.GetValue(instance);
if (rawValue == null) {
return false;
}

string stringValue = property.ValueProvider.GetValue(instance).ToString();
return !string.IsNullOrWhiteSpace(stringValue);
}
catch {
return true;
}
};
}

return property;
}
}

使用这个测试类:

public class TestClass {
public string WhiteSpace => " ";
public string Null = null;
public string Empty = string.Empty;
public string Value = "value";
}

这是输出:

{"Value":"value"}

关于c# - 如果 JSON.NET 中的值为 null 或空格,则阻止序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50840347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com