I need to convert my class to JSON and I use Json.NET. But I can have different JSON structures, like:
{
    name: "Name",
    type: "simple1",
    value: 100
};
or
{
    name: "Name",
    type: {
        optional1: {
            setting1: "s1",
            setting2: "s2",
            ///etc.
    },
    value: 100
};
My C# code is:
public class Configuration
{
    [JsonProperty(PropertyName = "name")]
    public string Name{ get; set; }
    [JsonProperty(PropertyName = "type")]
    public MyEnumTypes Type { get; set; }
    public OptionalType TypeAdditionalData { get; set; }
    [JsonProperty(PropertyName = "value")]
    public int Value { get; set; }
    public bool ShouldSerializeType()
    {
        OptionalSettingsAttribute optionalSettingsAttr = this.Type.GetAttributeOfType<OptionalSettingsAttribute>();
        return optionalSettingsAttr == null;
    }
    public bool ShouldSerializeTypeAdditionalData()
    {
        OptionalSettingsAttribute optionalSettingsAttr = this.Type.GetAttributeOfType<OptionalSettingsAttribute>();
        return optionalSettingsAttr != null;
    }
}
public enum MyEnumTypes 
{
    [EnumMember(Value = "simple1")]
    Simple1,
    [EnumMember(Value = "simple2")]
    Simple2,
    [OptionalSettingsAttribute]
    [EnumMember(Value = "optional1")]
    Optional1,
    [EnumMember(Value = "optional2")]
    [OptionalSettingsAttribute]
    Optional2
}
My idea was when Configuration.Type - value hasn't attribute OptionalSettingsAttribute - to serialize it as type: "simple1". Otherwise - to use Configuration.Type - value as type's value key (type: { optional1: {} }) and value in Configuration.TypeAdditionalData as optional1 - value (like 2 simple JSON above).
I tried to create a custom Converter, like:
public class ConfigurationCustomConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(Configuration).IsAssignableFrom(objectType);
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return serializer.Deserialize<Configuration>(reader);
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        //my changes here
        serializer.Serialize(writer, value);
    }
But when I add [JsonConverter(typeof(ConfigurationCustomConverter))] attribute to Configuration class:
[JsonConverter(typeof(ConfigurationCustomConverter))]
public class Configuration
and called JsonConvert.SerializeObject(configurationObj); I received next error:
Self referencing loop detected with type 'Configuration'. Path ''.
Do you have any ideas how to change my code to serialize my class to 2 different JSON structures? Note: I won't use the same class to deserialize the JSON.
Thank you!
