I have a class. It has several properties lets say 10. Out of these 10, 3 are filled with data remaining 7 are blank.i.e. empty strings \"\" Used this link as reference. I w
i have done this with a converter.
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace TestApp.JsonConverterResolver
{
public class IgnoreEmptyStringsConverter : JsonConverter
{
#region Methods
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
var theValue = reader.Value?.ToString();
return !string.IsNullOrWhiteSpace(theValue) ? theValue : null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (!string.IsNullOrWhiteSpace(value.ToString()))
{
JToken token = JToken.FromObject(value.ToString(), serializer);
token.WriteTo(writer);
return;
}
writer.WriteNull();
}
#endregion
}
}
Example person model class:
public class Person
{
public string Name { get; set; }
}
And the ueage:
var serializerSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
Converters = new List {new IgnoreEmptyStringsConverter()}
};
var person = JsonConvert.DeserializeObject("{ \"Name\":\"\" }", serializerSettings);
var jsonPerson = JsonConvert.SerializeObject(new Person { Name = "" }, serializerSettings);
I just wrote that out of my head. But I think that's how I solved it at some point. Maybe it helps someone.