Json Convert empty string instead of null

c#, json, null, string

Solution

This should work:

var settings = new JsonSerializerSettings() { ContractResolver= new NullToEmptyStringResolver() };
var str = JsonConvert.SerializeObject(yourObj, settings);
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Reflection;

public class NullToEmptyStringResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return type.GetProperties()
                .Select(p=>{
                    var jp = base.CreateProperty(p, memberSerialization);
                    jp.ValueProvider = new NullToEmptyStringValueProvider(p);
                    return jp;
                }).ToList();
    }
}

public class NullToEmptyStringValueProvider : IValueProvider
{
    PropertyInfo _MemberInfo;
    public NullToEmptyStringValueProvider(PropertyInfo memberInfo)
    {
        _MemberInfo = memberInfo;
    }

    public object GetValue(object target)
    {
        object result =  _MemberInfo.GetValue(target);
        if (_MemberInfo.PropertyType == typeof(string) && result == null) result = "";
        return result;
            
    }

    public void SetValue(object target, object value)
    {
        _MemberInfo.SetValue(target, value);
    }
}

Problem

I'm trying to serialize my struct so that the strings that didn't get a value get their default value "" instead of null ``` [JsonProperty(PropertyName = "myProperty", DefaultValueHandling = DefaultValueHandling.Populate)] [DefaultValue("")] public string MyProperty{ get; set; } ``` My result in the Json string: ``` "myProperty": null, ``` what i want ``` "myProperty": "", ``` I also tried creating a converter without any effect, the can Convert and WriteJson functions aren't even firing for some reason: ``` [JsonProperty(PropertyName = "myProperty")] [JsonConverter(typeof(NullToEmptyStringConverter))] public string MyProperty{ get; set; } class NullToEmptyStringConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(object[]); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) writer.WriteValue(""); } } ``` This isnt helping either Json.Net How to deserialize null as empty string?

Original source

Related problems