1

I have a custom converter for so I can ignore empty strings but the WriteJson method throws a stackoverflow exception. What's the proper way to write out the value here?

internal class StringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    public override object ReadJson(JsonReader reader, Type t, 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()))
        {
            serializer.Serialize(writer, value.ToString()); //stackoverflow error here
            return;
        }

        writer.WriteNull(); //how do I get it to skip the entry?
    }

    public static readonly StringConverter Singleton = new StringConverter();
}
rory
  • 1,490
  • 3
  • 22
  • 50
  • 2
    Would `writer.WriteString(...)` make more sense here? – Matthew May 06 '21 at 11:41
  • @Matthew - thanks. WriteValue does the trick. – rory May 06 '21 at 11:49
  • 1
    You can't use a custom converter to skip writing a value. Once `WriteJson()` is called the property name is already written. See: [Custom Json.NET converter should not serialize a property](https://stackoverflow.com/q/52671471/3744182). If you want to omit empty strings from an object, see [Remove empty string properties from json serialized object](https://stackoverflow.com/q/41287224/3744182). In fact this may be a duplicate of those two, agree? – dbc May 06 '21 at 14:32
  • 1
    @dbc I used https://stackoverflow.com/a/53878125/2297041 to skip the empty strings – rory May 07 '21 at 15:04
  • 1
    @rory - glad that worked! – dbc May 07 '21 at 15:26

0 Answers0