Код: Выделить всё
"events": [
{
"id": 1,
"actions": [
{
"id": 8,
"values": {
"obj_id":160,
"url": "https://www.myurl.com/"
}
},
{
"id":15,
"values":{
"obj_id":182,
"scale":200
}
}
]
}
]
Код: Выделить всё
public class Events
{
public int id;
public ActionsHolder[] actions;
}
[JsonConverter(typeof(BaseConverter))]
public class ActionsHolder
{
public int id { get; set; } = -1;
public ActionBase values { get; set; }
}
public abstract class ActionBase : ActionsHolder
{
public int obj_id { get; set; }
}
public class OpenURLAction : ActionBase
{
//Action id 8 = Open URL
public string url { get; set; }
}
public class ScaleAction : ActionBase
{
//Action id 15 = Scale
public float scale { get; set; } = 1;
}
Код: Выделить всё
public class BaseConverter : JsonConverter
{
static JsonSerializerSettings SpecifiedSubclassConversion = new JsonSerializerSettings()
{
ContractResolver = new BaseSpecifiedConcreteClassConverter() ,
TypeNameHandling = TypeNameHandling.All
};
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(ActionsHolder));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject joAction = JObject.Load(reader);
JObject joValues = (JObject)joAction["values"];
switch (joAction["id"].Value())
{
case 8:
return new ActionsHolder
{
id = joAction["id"].Value(),
values = JsonConvert.DeserializeObject(joValues.ToString(), SpecifiedSubclassConversion)
};
case 15:
return new ActionsHolder
{
id = joAction["id"].Value(),
values = JsonConvert.DeserializeObject(joValues.ToString(), SpecifiedSubclassConversion)
};
default:
return null;
}
throw new NotImplementedException();
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();returns false
}
}
Как мой пользовательский конвертер может десериализовать только свойства действий и конвертер по умолчанию для других...
Кто-нибудь может помочь?
п>
Подробнее здесь: https://stackoverflow.com/questions/783 ... ract-class