在 JsonSerializerSettings 中将 null 更改为空

changing null to empty in JsonSerializerSettings

我在 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
 }

一切正常,但我想 return“{}”而不是空列的空值。

{
   "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);
    }
}

另请参阅此答案: