Igor Mesaros Igor Mesaros - 2 months ago 56
JSON Question

Json Convert empty string instead of null

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?

L.B L.B
Answer

This should work:

var settings = new JsonSerializerSettings
{
    ContractResolver = new NullToEmptyStringResolver()
};

var str = JsonConvert.SerializeObject(yourObj, settings);

public class NullToEmptyStringResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        return type.GetProperties().Select(property => CreateProperty(property, memberSerialization)).ToList();
    }

    private JsonProperty CreateProperty(PropertyInfo property, MemberSerialization memberSerialization)
    {
        var jsonProperty = base.CreateProperty(property, memberSerialization);

        jsonProperty.ValueProvider = new NullToEmptyStringValueProvider(jsonProperty.ValueProvider, property);

        return jsonProperty;
    }

    private class NullToEmptyStringValueProvider : IValueProvider
    {
        private readonly IValueProvider _valueProvider;

        private readonly PropertyInfo _property;

        public NullToEmptyStringValueProvider(IValueProvider valueProvider, PropertyInfo property)
        {
            _valueProvider = valueProvider;
            _property = property;
        }

        public object GetValue(object target)
        {
            var result = _valueProvider == null
                ? _property.GetValue(target)
                : _valueProvider.GetValue(target);

            if (_property.PropertyType == typeof(string) && result == null)
            {
                result = string.Empty;
            }

            return result;
        }

        public void SetValue(object target, object value)
        {
            if (_valueProvider == null)
            {
                _property.SetValue(target, value);
            }
            else
            {
                _valueProvider.SetValue(target, value);
            }
        }
    }
}
Comments