在JsonSerializerSettings中将null更改为空

时间:2015-02-25 14:00:01

标签: c# json asp.net-mvc serialization

我在我的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。

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

有什么配置可以帮我吗?

1 个答案:

答案 0 :(得分:2)

您需要调整自定义的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