我正在使用C#在我的asp.net mvc项目中使用Azure缓存作为缓存提供程序
我使用这种方法通过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
 }


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

{
   "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/

10-16 08:54