gpt4 book ai didi

c# - 在 JsonSerializerSettings 中将 null 更改为空

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:47 30 4
gpt4 key购买 nike

我在我的 asp.net mvc 项目中使用 azure 缓存作为缓存提供程序与 c#我使用此方法通过 JsonSerializerSettings 序列化我的数据

public static JsonSerializerSettings GetDefaultSettings()
{
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
Binder = new TypeManagerSerializationBinder(),
ContractResolver = new PrivateSetterContractResolver()
};
settings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.RoundtripKind });
return settings;
}

我的对象是这样的

{
"Name": "Bad Boys III",
"Description": "It's no Bad Boys",
"Classification": null,
"Studio": null,
"ReleaseCountries": null
}

一切正常,但我想为 null 列返回“{}”而不是 null。

{
"Name": "Bad Boys III",
"Description": "It's no Bad Boys",
"Classification": {},
"Studio": {},
"ReleaseCountries": {}
}

有什么配置可以帮我做到这一点吗?

最佳答案

您需要调整您的自定义 ContractResolver。它可能看起来像这样(我没有测试):

JsonSerializerSettings settings = new JsonSerializerSettings 
{
...
ContractResolver= new MyCustomContractResolver()
};

public class MyCustomContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return type.GetProperties().Select( p =>
{
var property = base.CreateProperty(p, memberSerialization);
property.ValueProvider = new MyCustomNullValueProvider(p);
return property;
}).ToList();
}
}

public class MyCustomNullValueProvider : IValueProvider
{
PropertyInfo _MemberInfo;
public MyCustomNullValueProvider(PropertyInfo memberInfo)
{
_MemberInfo = memberInfo;
}

public object GetValue(object target)
{
object value = _MemberInfo.GetValue(target);
if (value == null)
result = "{}";
else
return value;
}

public void SetValue(object target, object value)
{
if ((string)value == "{}")
value = null;
_MemberInfo.SetValue(target, value);
}
}

另请参阅此答案:https://stackoverflow.com/a/23832417/594074

关于c# - 在 JsonSerializerSettings 中将 null 更改为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28720925/

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