Mini
Mini

Reputation: 1170

changing null to empty in JsonSerializerSettings

I'm using azure cache as caching provider in my asp.net mvc project with c# and I use this method to serialize my data with 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;
        }

my object is like this

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

everything is Ok but I want to return "{}" instead of null for null columns.

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

is there any config to do that for me?

Upvotes: 3

Views: 3225

Answers (1)

Baris Akar
Baris Akar

Reputation: 4965

You need to adapt your custom ContractResolver. It could look like this (I didn't test it):

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

Also see this answer: https://stackoverflow.com/a/23832417/594074

Upvotes: 3

Related Questions