1

I have write a small compactify json conveter for internal elements of collections

public class CompactConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return true;            
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return serializer.Deserialize(reader);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var formating = writer.Formatting;
        writer.Formatting = Formatting.None;
        serializer.Serialize(writer, value);
        writer.Formatting = formating;            
    }
}

and somewhere in the depths of my serializing object there such items:

[JsonConverter(typeof(CompactConverter))]
public class DynamicUtilParam
{
    public string Name { get; set; }

    public int Field { get; set; }

    public bool IsDate { get; set; }

    public string Comment { get; set; }

    [OnSerializing]
    internal void OnSerializing(StreamingContext content)
    {
        if (string.IsNullOrEmpty(this.Comment))
        {
            this.Comment = null;
        }
    }

    [OnDeserialized]
    internal void OnDeserialized(StreamingContext context)
    {
        if (this.Comment == null)
        {
            this.Comment = string.Empty;
        }
    }
}

if I comment JsonConverterAttribute everything serializes fine, but internal elements are not compact. I a try to serialized it with this attribute, the result is "Self referencing loop detected with type 'ConfigurationConverter.DynamicUtilParam'. Path 'UtilParams'."

serialized = JsonConvert.SerializeObject(config, Formatting.Indented,
                    new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    }
                });

What is the cause and how can I solve it?

P.S.: If I debug through JsonSerializerInternalWriter I can find that _serializeStack.Contains(value) is true.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
Anton
  • 11
  • 2
  • Use `NoFormattingConverter` from [Newtonsoft inline formatting for subelement while serializing](https://stackoverflow.com/a/30833722/3744182). The converter needs to disable itself temporarily to prevent recursive self-calls. MCVE: https://dotnetfiddle.net/Z7vRiL. Demo of fix: https://dotnetfiddle.net/97FT7t – dbc Dec 17 '18 at 16:07

0 Answers0