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);
}
}
Related
I have the following class...
public class ResultDTO
{
public string MSAccountNumber { get; set; }
public string MSCaseNumber { get; set; }
public string StatusMessage { get; set; }
public string StatCode { get; set; }
}
Unsurprisingly, JsonConvert.DeserializeObject is unable to convert the following JSON into that object....
{
"StatusMessage": [
"Record processed successfully"
],
"StatCode": [
"200"
],
"MSCaseNumber": [
"500"
],
"MSAccountNumber": [
"001"
]
}
I have asked the API creator if he can change the API so that the returned JSON has string properties instead of List<string> properties. But in case he is unable to accommodate that, how do I implement and use a JsonConverter so that JsonConvert will successfully convert that JSON into my target class. Assume that all of the List properties in the JSON will have at least one item (is never null or empty) and we want to take the first item.
I know this can be done but I have no idea how.
Here is a converter that should work for you:
class StringArrayToStringConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null) return null;
if (reader.TokenType == JsonToken.String) return (string)reader.Value;
if (reader.TokenType == JsonToken.StartArray)
{
JArray array = JArray.Load(reader);
string value = (string)array.Children<JValue>().FirstOrDefault();
return value;
}
throw new JsonException("Unexpected token type: " + reader.TokenType);
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Use it like this:
var dto = JsonConvert.DeserializeObject<ResultDTO>(json, new StringArrayToStringConverter());
Working demo: https://dotnetfiddle.net/kLbn2P
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
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;
I have the following JSON data which I'd like to deserialize to a C# POCO object but I'm having trouble deserializing the array of arrays.
var json = #"{
""name"": ""Foo"",
""pages"": [
{
""page"": 1,
""fields"": [
{
""name"": ""stuffs"",
""rows"": [
[{ ""value"" : ""$199""}, { ""value"": ""foo"" }],
[{ ""value"" : ""$222""}, { ""value"": ""bar"", ""color"": ""blue"" }]
]
}]
}
]
}";
The exception is
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'UserQuery+TableRow' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'rows[0]', line 4, position 5.
Following the advise of the exception message, I did attempt all of those things but only to be faced with more errors.
These are my POCO objects
public class Document
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("pages")]
public Page[] Pages { get; set; }
}
public class Page
{
[JsonProperty("page")]
public int PageNumber { get; set; }
[JsonProperty("fields")]
public FieldBase[] FieldsBase { get; set; }
}
public class TableRow
{
public Cell[] Cells { get; set; }
}
public class Cell
{
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("color")]
public string Color { get; set; }
}
public abstract class FieldBase
{
[JsonProperty("name")]
public string Name { get; set; }
}
public class Table : FieldBase
{
[JsonProperty("rows")]
public TableRow[] Rows { get; set; } = new TableRow[0];
}
And my field converter to deal with the abstract class (not sure if this matters)
public class FieldConverter : JsonConverter
{
static JsonSerializerSettings SpecifiedSubclassConversion = new JsonSerializerSettings() { ContractResolver = new BaseSpecifiedConcreteClassConverter() };
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(FieldBase));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
return JsonConvert.DeserializeObject<Table>(jo.ToString(), SpecifiedSubclassConversion);
}
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
}
}
public class BaseSpecifiedConcreteClassConverter : DefaultContractResolver
{
protected override JsonConverter ResolveContractConverter(Type objectType)
{
if (typeof(FieldBase).IsAssignableFrom(objectType) && !objectType.IsAbstract)
return null; // pretend TableSortRuleConvert is not specified (thus avoiding a stack overflow)
return base.ResolveContractConverter(objectType);
}
}
And the following line of code which, when executed in LINQPad, produces the error
JsonConvert.DeserializeObject<Document>(json, new FieldConverter()).Dump();
Any help would be greatly appreciated.
In your json, "rows" is a jagged array:
"rows": [[{ "value" : "$199"}, { "value": "foo" }]]
However, in your object model this corresponds to an array of TableRow classes that contain an array of cells. Thus you will need another JsonConverter to serialize each TableRow as an array of cells and not an object:
public class TableRowConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TableRow);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var cells = serializer.Deserialize<Cell[]>(reader);
return new TableRow { Cells = cells };
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var row = (TableRow)value;
serializer.Serialize(writer, row.Cells);
}
}
public class JsonDerivedTypeConverter<TBase, TDerived> : JsonConverter where TDerived : TBase
{
public JsonDerivedTypeConverter()
{
if (typeof(TBase) == typeof(TDerived))
throw new InvalidOperationException("TBase and TDerived cannot be identical");
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(TBase);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize<TDerived>(reader);
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then, to deserialize, do:
var settings = new JsonSerializerSettings
{
Converters = new JsonConverter[] { new TableRowConverter(), new JsonDerivedTypeConverter<FieldBase, Table>() },
};
var doc = JsonConvert.DeserializeObject<Document>(json, settings);
Example fiddle.
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;
}
}