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.