3

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?

Mini
  • 1,138
  • 9
  • 24
  • string Json = jsonstring.Replace("null", "{}"); – sakir Feb 25 '15 at 17:44
  • I'm using this method to deserialize ________ public object Deserialize(Stream stream) { JsonSerializer serializer = JsonSerializer.Create(this.Settings); JsonReader reader = new JsonTextReader(new StreamReader(stream, Encoding.UTF8)); return serializer.Deserialize(reader); } – Mini Feb 25 '15 at 17:52
  • not sure but u can try use this [DefaultValue("")] public string FollowUpEmailAddress { get; set; } on yor model,intead of empty text , an empty jsononject – sakir Feb 25 '15 at 17:58
  • refrence http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm – sakir Feb 25 '15 at 17:59
  • @Amir: My original answer was probably wrong and wouldn't have worked, so I updated it. Adapting your custom ContractResolver should be the way to go for you, see my updated answer... – Baris Akar Feb 26 '15 at 08:49

1 Answers1

3

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

Community
  • 1
  • 1
Baris Akar
  • 4,895
  • 1
  • 26
  • 54