我需要將我的類轉換爲JSON,並使用Json.NET。但是,我可以有不同的JSON結構,比如:Json.NET不同的JSON結構,基於枚舉值
{
name: "Name",
type: "simple1",
value: 100
};
或
{
name: "Name",
type: {
optional1: {
setting1: "s1",
setting2: "s2",
///etc.
},
value: 100
};
我的C#代碼是:
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
}
我的想法是,當Configuration.Type
- 值沒有屬性OptionalSettingsAttribute
- 將其序列化爲type: "simple1"
。否則 - 使用Configuration.Type
- 值作爲類型的值鍵(type: { optional1: {} }
),值Configuration.TypeAdditionalData
爲optional1
- 值(如上面的2個簡單的JSON)。
我試圖創建一個自定義的轉換器,如:
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);
}
但是當我添加[JsonConverter(typeof(ConfigurationCustomConverter))]
屬性Configuration
類:
[JsonConverter(typeof(ConfigurationCustomConverter))]
public class Configuration
,並呼籲JsonConvert.SerializeObject(configurationObj);
,我收到一個錯誤:
Self referencing loop detected with type 'Configuration'. Path ''.
你有什麼想法如何改變我的代碼將我的類序列化爲2個不同的JSON結構? 注意:我不會使用相同的類來反序列化JSON。
謝謝!
非常感謝@dbc!我嘗試瞭解決方案#3,它爲我工作! – Pepo