Simplifying Json entity for deserialisation - c#

Actually I receive Json like this:
{
"id" : 1,
"items": [
{
"media": {
"id": 1,
}
},
{
"media": {
"id": 2,
},
}
],
"status": "ok"
}
I created class like this to map on entity
public class Message
{
[JsonProperty("items")]
public List<Item> Items { get; set; }
}
public class Item
{
[JsonProperty("media")]
public Media Media { get; set; }
}
public class Media
{
[JsonProperty("id")]
public string Id { get; set; }
}
This work perfectly but my question is:
Is it possible to remove Item class and directly cast in List of Media to simplify ?
Update:
I'm pretty sure it is possible, the first way I found before post is JSonConverter, but I'm not sure is the best way to do that, i would like to know if there are any easier solution, with attribute for example.

Using a private Dictionary
Yes, you can, for example using a (private) Dictionary
public class Message
{
public List<Media> Items { get; set; }
}
public class Media
{
[JsonProperty("media")]
private Dictionary<string, string> IdDict;
public string Id
{
get { return IdDict["id"]; }
set { IdDict["id"] = value; }
}
}
Usage
var result = JsonConvert.DeserializeObject<Message>(json);
var test = result.Items[1].Id;
Implementing a Converter
Alternatively you can achieve your result by implementing a Converter
public class MediaConverter : JsonCreationConverter<Message>
{
protected override Message Create(Type objectType, JObject jObject)
{
var msg = new Message();
msg.Items = new List<Media>();
foreach (var item in jObject["items"])
{
Media media = new Media();
media.Id = item["media"]["id"].Value<string>();
msg.Items.Add(media);
}
return msg;
}
}
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
// Load JObject from stream
JObject jObject = JObject.Load(reader);
// Create target object based on JObject
T target = Create(objectType, jObject);
return target;
}
public override void WriteJson(JsonWriter writer,
object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Usage
var result = JsonConvert.DeserializeObject<Message>(json, new MediaConverter());
var test = result.Items[1].Id;

Related

Use JsonConverter to deserialize JToken to bool

I have an odd JSON object I need to deserialize.
{
"data": {
"id": 123,
"permissions": {
"appName": {
"data": {
"1": {
"2021-08-01": {
"2020": {
"isAllowed": {}
}
}
}
}
}
}
}
}
I've gotten most of it to work with a wrapper and nested dictionaries but the final part isn't working as expected. It works fine if I create a class like this, but using it is clunky.
public class DataWrapper<T>
{
public T Data { get; set;}
}
public class PermissionValues
{
public JToken IsAllowed { get; set; }
}
DataWrapper<Dictionary<int, Dictionary<DateTime, Dictionary<int, PermissionValues>>>>
I'd like to change JToken to a bool. When I do that and add a JsonConverter
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return true; //{} is true but JSON.net parses as null, old was: reader.Value != null;
}
I get an error:
Newtonsoft.Json.JsonSerializationException: 'Could not convert string
'isAllowed' to dictionary key type 'System.Int32'. Create a
TypeConverter to convert from the string to the key type object. Path
'data.permissions.appName.data.1.2021-08-01.2020.isAllowed'
Any idea what I am missing?
Use JToken.ToObject()
string json = "{\"data\":{\"id\":123,\"permissions\":{\"appName\":{\"data\":{\"1\":{\"2021-08-01\":{\"2020\":{\"isAllowed\":{}}}}}}}}}";
var jToken= JToken.Parse(json).SelectToken("$.data.permissions.appName");
var result = jToken.ToObject<DataWrapper<Dictionary<int, Dictionary<DateTime, Dictionary<int, PermissionValues>>>>>();
Use the JsonConvertor Attribute on IsAllowed Property.
public class DataWrapper<T>
{
public T Data { get; set; }
}
public class PermissionValues
{
[JsonConverter(typeof(BoolConverter))]
public bool IsAllowed { get; set; }
}
public class BoolConverter : JsonConverter
{
//Implement other abstract functions
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value != null;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(bool);
}
}

Deserialize an abstract class that has only a getter using Newtonsoft

I'm trying to deseralize JSON I'm getting:
[
{
"Name":"0",
"Health":0,
"TypeName":"SpellInfo",
"Info":{
"Effect":1,
"EffectAmount":4
}
},
{
"Name":"1",
"Health":0,
"TypeName":"MonsterInfo",
"Info":{
"Health":10,
"AttackDamage":10
}
},
...
...
]
Created a class to handle the JSON:
[System.Serializable]
public class CardDataStructure
{
public string Name;
public int Health;
public string TypeName;
public Info Info;
}
I managed to get all the info I needed but the Info. From the research I did, I created a JsonConverter from a link - https://blog.codeinside.eu/2015/03/30/json-dotnet-deserialize-to-abstract-class-or-interface/
Which is actually pretty close,
public class InfoConvert: JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Info));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
if (jo.ToString().Contains("Effect"))
{
if (jo["Effect"].Value<string>() is string)
return jo.ToObject<SpellInfo>(serializer);
}
if (jo.ToString().Contains("Health"))
{
if (jo["Health"].Value<string>() is string)
return jo.ToObject<MonsterInfo>(serializer);
}
return null;
}
}
(It would have been better to find it by 'typename' but I couldn't figure out how to do that, so went with something simple)
When checking 'jo', the properties are there and go to the correct class yet once out of the converter I get default properties and not the once the converter showed.
I can't find the link but on the Newtonsoft doc it said somewhere there's a problem with deserializing an abstract class and if the abstract class doesn't have a public setter.
Both monsterinfo and spellinfo inherit from info:
[Serializable]
public abstract class Info
{
}
The monsterinfo and spellinfo look basically the same. Problem is they don't have a public setters and I cannot change them right now.
{
[Serializable]
public class MonsterInfo: Info
{
[SerializeField]
private int m_Health;
public int Health => m_Health;
[SerializeField]
private int m_AttackDamage;
public int AttackDamage => m_AttackDamage;
}
}
So, when trying to deseralize the JSON:
string contents = File.ReadAllText(source);
contents = "{\"cards\":" + contents + "}";
JsonConverter[] converters = { new InfoConvert() };
cardsData = JsonConvert.DeserializeObject<Cards>(contents, new JsonSerializerSettings() {
Converters = converters, NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.Auto});
*Cards is a list of CardDataStructure
Is it even possible to get the data in Info without giving them a public setter?
Best I got is all the data inside the JSON and an empty Monster/Spell Info.
At the end I just need to parse the json I'm getting, but while the 'name', 'health', 'typeinfo' are parsed correctly, info is always an empty object filled with 0s.
Edit: Corrected some things.
You should do that like this dude:
A marker interface for detecting the type or deserializing
A container class
Dto classes
//marker interface
public interface Info { }
public class HealthInfo : Info
{
public int MoreHealth { set; get; }
public int AttackDamage { set; get; }
}
public class SpellInfo : Info
{
public int Effect { set; get; }
public int EffectAmount { set; get; }
}
public class Card<T> where T : Info
{
public Card(string name, int health, T info)
{
this.Info = info;
this.Name = name;
this.Health = health;
}
public T Info { private set; get; }
public string Name { set; get; }
public int Health { set; get; }
}
public class InfoConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
if (objectType == typeof(Card<Info>))
{
return true;
}
return false;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jObject = JObject.Load(reader);
if (jObject.ContainsKey("TypeName"))
{
string typeName = jObject["TypeName"]?.ToString()?.Trim()?.ToLower();
if (typeName?.Equals("monsterinfo") == true)
{
Card<HealthInfo> deseerialized = jObject.ToObject<Card<HealthInfo>>();
return new Card<Info>(deseerialized.Name, deseerialized.Health, deseerialized.Info);
}
if (typeName?.Equals("spellinfo") == true)
{
string json = jObject.ToString();
Card<SpellInfo> deseerialized = jObject.ToObject<Card<SpellInfo>>();
return new Card<Info>(deseerialized.Name, deseerialized.Health, deseerialized.Info);
}
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
And you should execute:
List<Card<Info>> list = JsonConvert.DeserializeObject<List<Card<Info>>>(jsonText, new InfoConverter());

Newtonsoft JsonConvert.DeserializeObject how to ignore empty objects

I have the following class definitions:
public class Tag
{
public Guid? TagId { get; set; }
public string TagText { get; set; }
public DateTime CreatedOn { get; set; }
}
public class Wiki
{
public Guid? WikiId { get; set; }
public string WikiText { get; set; }
public string Title { get; set; }
public DateTime CreatedOn { get; set; }
public IEnumerable<Tag> Tags { get; set; }
}
From the database i get the following json Object:
{
"WikiId": "83981284-0AD3-4420-90AB-15E3BF6BD7B7",
"WikiText": "Text",
"Title": "Title",
"CreatedOn": "2017-08-07T09:16:06.0800000",
"Tags": [{}] // <-- here i would like to ignore the empty Tag object
}
When i do now a JsonConvert.DeserializeObject<Wiki>(json) i get a Wiki object with a list of 1 Tag with the values TagId: null, TagText: null and CreatedOn: "0001-01-01T00:00:00"
Is there a way to ignore the empty Tag object while deserializing? I have tried several JsonSerializerSettings but nothing helped.
You could use a custom JsonConverter to ignore the empty objects during deserialization. Something like this could work:
class IgnoreEmptyItemsConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsAssignableFrom(typeof(List<T>));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
List<T> list = new List<T>();
JArray array = JArray.Load(reader);
foreach (JObject obj in array.Children<JObject>())
{
if (obj.HasValues)
{
list.Add(obj.ToObject<T>(serializer));
}
}
return list;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use the converter, just add a [JsonConverter] attribute to your Tags property like this:
public class Wiki
{
...
[JsonConverter(typeof(IgnoreEmptyItemsConverter<Tag>))]
public IEnumerable<Tag> Tags { get; set; }
}
Fiddle: https://dotnetfiddle.net/hrAFsh
You'll have to detect the empty tag objects post-conversion and remove them yourself. From the deserializer's perspective, {} is a perfectly valid and complete Tag object whose properties are all unset.
Something like the following should work (presuming C# 6):
Wiki wiki = JsonConvert.DeserializeObject<Wiki>(json);
wiki.Tags = Wiki.Tags?.Where(x => x.TagId.HasValue)?.ToList();
Thanks to #Brian-Rogers's brilliant answer, I was able to come up with a non-generic solution which will work on all collections instead of List only:
public class IgnoreEmptyArrayItemsConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
bool result = typeof(System.Collections.IEnumerable).IsAssignableFrom(objectType);
return result;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var tokenIndexesToRemove = new List<int>();
var array = JArray.Load(reader);
for (int i = 0; i < array.Count; i++)
{
var obj = array[i];
if (!obj.HasValues)
tokenIndexesToRemove.Add(i);
}
foreach (int index in tokenIndexesToRemove)
array.RemoveAt(index);
var result = array.ToObject(objectType, serializer);
return result;
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Instead of looping through the objects, deserializing them and adding them to a hardcoded List collection one by one, this solution will just remove the faulting tokens from the JArray and let the library deserialize the whole array to the type it should be.
Usage:
public class Wiki
{
...
[JsonConverter(typeof(IgnoreEmptyItemsConverter))] // No generic parameter needed
public HashSet<Tag> Tags { get; set; }
}
Fiddle: https://dotnetfiddle.net/9FCcpD

Deserialize Mixpanel Data API Event JSON C#

I'm trying to deserialize some json from the mixpanel data api using Newtonsoft Json, I've created a class, but I get errors. The problem lies with the fact that property A and B in the 'values' object aren't fixed names. Hence why I thought using Dictionary<string, NameValueCollection> would work. Any help with this would be great
JSON:
{
"legend_size": 1,
"data": {
"series": [
"2014-06-30"
],
"values": {
"A": {
"2014-06-30": 1082,
"2014-06-23": 4249
},
"B": {
"2014-06-30": 1082,
"2014-06-23": 4249
}
}
}
}
Results.cs
public class Result
{
[JsonProperty("data")]
public Data Data { get; set; }
[JsonProperty("legend_size")]
public int LegendSize { get; set; }
}
public class Data
{
[JsonProperty("series")]
public IEnumerable<DateTime> Series { get; set; }
[JsonConverter(typeof(MixEventValuesConverter))]
[JsonProperty("values")]
public IDictionary<string, NameValueCollection> Values { get; set; }
}
I created a converter (for the first time ever, i don't really know what I'm doing with it!) and tried to return just an empty value for now, but I get the error 'Additional text found in JSON string after finishing deserializing object.'.
MixEventValuesConverter.cs
public class MixEventValuesConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var col = new NameValueCollection();
col.Add("testtest", "vallll");
var dic = new Dictionary<string, NameValueCollection>();
dic.Add("testt", col);
return dic;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MixEventResult);
}
}
You don't need a converter here; just use a nested Dictionary like this:
public class Data
{
[JsonProperty("series")]
public IEnumerable<DateTime> Series { get; set; }
[JsonProperty("values")]
public IDictionary<string, IDictionary<DateTime, int>> Values { get; set; }
}

Deserializing JSON to abstract class

I am trying to deserialize a JSON string to a concrete class, which inherits from an abstract class, but I just can't get it working. I have googled and tried some solutions but they don't seem to work either.
This is what I have now:
abstract class AbstractClass { }
class ConcreteClass { }
public AbstractClass Decode(string jsonString)
{
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.TypeNameHandling = TypeNameHandling.All;
return (AbstractClass)JsonConvert.DeserializeObject(jsonString, null, jss);
}
However, if I try to cast the resulting object, it just doesn't work.
The reason why I don't use DeserializeObject is that I have many concrete classes.
Any suggestions?
I am using Newtonsoft.Json
One may not want to use TypeNameHandling (because one wants more compact json or wants to use a specific name for the type variable other than "$type"). Meanwhile, the customCreationConverter approach will not work if one wants to deserialize the base class into any of multiple derived classes without knowing which one to use in advance.
An alternative is to use an int or other type in the base class and define a JsonConverter.
[JsonConverter(typeof(BaseConverter))]
abstract class Base
{
public int ObjType { get; set; }
public int Id { get; set; }
}
class DerivedType1 : Base
{
public string Foo { get; set; }
}
class DerivedType2 : Base
{
public string Bar { get; set; }
}
The JsonConverter for the base class can then deserialize the object based on its type. The complication is that to avoid a stack overflow (where the JsonConverter repeatedly calls itself), a custom contract resolver must be used during this deserialization.
public class BaseSpecifiedConcreteClassConverter : DefaultContractResolver
{
protected override JsonConverter ResolveContractConverter(Type objectType)
{
if (typeof(Base).IsAssignableFrom(objectType) && !objectType.IsAbstract)
return null; // pretend TableSortRuleConvert is not specified (thus avoiding a stack overflow)
return base.ResolveContractConverter(objectType);
}
}
public class BaseConverter : JsonConverter
{
static JsonSerializerSettings SpecifiedSubclassConversion = new JsonSerializerSettings() { ContractResolver = new BaseSpecifiedConcreteClassConverter() };
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Base));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
switch (jo["ObjType"].Value<int>())
{
case 1:
return JsonConvert.DeserializeObject<DerivedType1>(jo.ToString(), SpecifiedSubclassConversion);
case 2:
return JsonConvert.DeserializeObject<DerivedType2>(jo.ToString(), SpecifiedSubclassConversion);
default:
throw new Exception();
}
throw new NotImplementedException();
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException(); // won't be called because CanWrite returns false
}
}
That's it. Now you can use serialize/deserialize any derived class. You can also use the base class in other classes and serialize/deserialize those without any additional work:
class Holder
{
public List<Base> Objects { get; set; }
}
string json = #"
[
{
""Objects"" :
[
{ ""ObjType"": 1, ""Id"" : 1, ""Foo"" : ""One"" },
{ ""ObjType"": 1, ""Id"" : 2, ""Foo"" : ""Two"" },
]
},
{
""Objects"" :
[
{ ""ObjType"": 2, ""Id"" : 3, ""Bar"" : ""Three"" },
{ ""ObjType"": 2, ""Id"" : 4, ""Bar"" : ""Four"" },
]
},
]";
List<Holder> list = JsonConvert.DeserializeObject<List<Holder>>(json);
string serializedAgain = JsonConvert.SerializeObject(list);
Debug.WriteLine(serializedAgain);
I would suggest to use CustomCreationConverter in the following way:
public enum ClassDiscriminatorEnum
{
ChildClass1,
ChildClass2
}
public abstract class BaseClass
{
public abstract ClassDiscriminatorEnum Type { get; }
}
public class Child1 : BaseClass
{
public override ClassDiscriminatorEnum Type => ClassDiscriminatorEnum.ChildClass1;
public int ExtraProperty1 { get; set; }
}
public class Child2 : BaseClass
{
public override ClassDiscriminatorEnum Type => ClassDiscriminatorEnum.ChildClass2;
}
public class BaseClassConverter : CustomCreationConverter<BaseClass>
{
private ClassDiscriminatorEnum _currentObjectType;
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jobj = JObject.ReadFrom(reader);
_currentObjectType = jobj["Type"].ToObject<ClassDiscriminatorEnum>();
return base.ReadJson(jobj.CreateReader(), objectType, existingValue, serializer);
}
public override BaseClass Create(Type objectType)
{
switch (_currentObjectType)
{
case ClassDiscriminatorEnum.ChildClass1:
return new Child1();
case ClassDiscriminatorEnum.ChildClass2:
return new Child2();
default:
throw new NotImplementedException();
}
}
}
try something like this
public AbstractClass Decode(string jsonString)
{
var jss = new JavaScriptSerializer();
return jss.Deserialize<ConcreteClass>(jsonString);
}
UPDATE
for this scenario methinks all work as you want
public abstract class Base
{
public abstract int GetInt();
}
public class Der:Base
{
int g = 5;
public override int GetInt()
{
return g+2;
}
}
public class Der2 : Base
{
int i = 10;
public override int GetInt()
{
return i+17;
}
}
....
var jset = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };
Base b = new Der()
string json = JsonConvert.SerializeObject(b, jset);
....
Base c = (Base)JsonConvert.DeserializeObject(json, jset);
where c type is test.Base {test.Der}
UPDATE
#Gusman suggest use TypeNameHandling.Objects instead of TypeNameHandling.All. It is enough and it will produce a less verbose serialization.
Actually, as it has been stated in an update, the simplest way (in 2019) is to use a simple custom pre-defined JsonSerializerSettings, as explained here
string jsonTypeNameAll = JsonConvert.SerializeObject(priceModels, Formatting.Indented,new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
And for deserializing :
TDSPriceModels models = JsonConvert.DeserializeObject<TDSPriceModels>(File.ReadAllText(jsonPath), new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
public class CustomConverter : JsonConverter
{
private static readonly JsonSerializer Serializer = new JsonSerializer();
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var typeString = jObject.Value<string>("Kind"); //Kind is a property in json , from which we know type of child classes
var requiredType = RecoverType(typeString);
return Serializer.Deserialize(jObject.CreateReader(), requiredType);
}
private Type RecoverType(string typeString)
{
if (typeString.Equals(type of child class1, StringComparison.OrdinalIgnoreCase))
return typeof(childclass1);
if (typeString.Equals(type of child class2, StringComparison.OrdinalIgnoreCase))
return typeof(childclass2);
throw new ArgumentException("Unrecognized type");
}
public override bool CanConvert(Type objectType)
{
return typeof(Base class).IsAssignableFrom(objectType) || typeof((Base class) == objectType;
}
public override bool CanWrite { get { return false; } }
}
Now add this converter in JsonSerializerSettings as below
var jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
jsonSerializerSettings.Converters.Add(new CustomConverter());
After adding serialize or deserialize base class object as below
JsonConvert.DeserializeObject<Type>("json string", jsonSerializerSettings );
I had a similar issue, and I solved it with another way, maybe this would help someone:
I have json that contains in it several fields that are always the same, except for one field called "data" that can be a different type of class every time.
I would like to de-serialize it without analayzing every filed specific.
My solution is:
To define the main class (with 'Data' field) with , the field Data is type T.
Whenever that I de-serialize, I specify the type:
MainClass:
public class MainClass<T>
{
[JsonProperty("status")]
public Statuses Status { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("data")]
public T Data { get; set; }
public static MainClass<T> Parse(string mainClsTxt)
{
var response = JsonConvert.DeserializeObject<MainClass<T>>(mainClsTxt);
return response;
}
}
User
public class User
{
[JsonProperty("id")]
public int UserId { get; set; }
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
}
Product
public class Product
{
[JsonProperty("product_id")]
public int ProductId { get; set; }
[JsonProperty("product_name")]
public string ProductName { get; set; }
[JsonProperty("stock")]
public int Stock { get; set; }
}
Using
var v = MainClass<User>.Parse(userJson);
var v2 = MainClass<Product>.Parse(productJson);
json example
userJson: "{"status":1,"description":"my description","data":{"id":12161347,"first_name":"my fname","last_name":"my lname"}}"
productJson: "{"status":1,"description":"my description","data":{"product_id":5,"product_name":"my product","stock":1000}}"
public abstract class JsonCreationConverter<T> : JsonConverter
{
protected abstract T Create(Type objectType, JObject jObject);
public override bool CanConvert(Type objectType)
{
return typeof(T) == objectType;
}
public override object ReadJson(JsonReader reader,Type objectType,
object existingValue, JsonSerializer serializer)
{
try
{
var jObject = JObject.Load(reader);
var target = Create(objectType, jObject);
serializer.Populate(jObject.CreateReader(), target);
return target;
}
catch (JsonReaderException)
{
return null;
}
}
public override void WriteJson(JsonWriter writer, object value,
JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Now implement this interface
public class SportActivityConverter : JsonCreationConverter<BaseSportActivity>
{
protected override BaseSportActivity Create(Type objectType, JObject jObject)
{
BaseSportActivity result = null;
try
{
switch ((ESportActivityType)jObject["activityType"].Value<int>())
{
case ESportActivityType.Football:
result = jObject.ToObject<FootballActivity>();
break;
case ESportActivityType.Basketball:
result = jObject.ToObject<BasketballActivity>();
break;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex);
}
return result;
}
}

Categories

Resources