Customizing the Converter for Json.NET

Many recently days, I thought about Json.net library that implemented by James. It is really a good library that I have ever used. I really impressed about many Converters that this library expose for user. I can list some converter of json.net at here:


+ BinaryConverter
+ BsonObjectIdConverter
+ DataSetConverter
+ DataTableConverter
+ EntityKeyMemberConverter
+ HtmlColorConverter
+ IsoDateTimeConverter
+ JavaScriptDateTimeConverter
+ KeyValuePairConverter
+ RegexConverter
+ StringEnumConverter
+ XmlNodeConverter


As you see, json.net have many converters, but still not enough for our necessary. So in this post, I try to explorer about 2 converters that I thought it is very useful for us. That are ArrayConverter and Object Converter (it is named by me). In 2 converter, I mainly implement it for return the object's interface, so it can be re-use and extension better. Now this is my code for implement it:
+ CustomObjectCreationConverter

    internal class CustomObjectCreationConverter<TInterfaceT> : CustomCreationConverter<TInterface>
        where T : TInterfacenew()
    {
        public override TInterface Create(Type objectType)
        {
            return new T();
        }
    }


+ CustomArrayCreationConverter

    internal class CustomArrayCreationConverter<TInterfaceT> : JsonConverter
        where T : TInterface
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(TInterface[]).IsAssignableFrom(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var list = new List<T>();
            serializer.Populate(reader, list);

            return list.ConvertAll(item => (TInterface)item).ToArray();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotSupportedException();
        }
    }

And I also wrapped the Serialize of Json.net as:
    public static class JsonHelper
    {
        public static T DeserializeObject<T>(string inputString)
        {
            return JsonConvert.DeserializeObject<T>(inputString);
        }

        public static string SerializeObject<T>(T inputObject)
        {
            return JsonConvert.SerializeObject(inputObject);
        }
    }


Now I have a simple example for using it
I assume that we have a JSON data is:

{ "categories" : [{
 "detailInformation" : {
  "name" : "category 1",
  "shortName" : "cat 1",
  "description" : "description for category 1"
 },
 "listOfNews" : [{
   "title" : "news1's title",
   "mainContent" : "this is a main content of news 1",
   "createdDate" : "",
   "description" : "description for news 1"
  },
  {
   "title" : "news2's title",
   "mainContent" : "this is a main content of news 2",
   "createdDate" : "",
   "description" : "description for news 2"
  }
 ]},{
 "detailInformation" : {
  "name" : "category 2",
  "shortName" : "cat 2",
  "description" : "description for category 2"
 },
 "listOfNews" : [{
   "title" : "news1's title",
   "mainContent" : "this is a main content of news 1",
   "createdDate" : "",
   "description" : "description for news 1"
  },
  {
   "title" : "news2's title",
   "mainContent" : "this is a main content of news 2",
   "createdDate" : "",
   "description" : "description for news 2"
  }
 ]}
]} 

and the entities is

    public interface IDetailInformation
    {
        string Name { getset; }

        string ShortName { getset; }

        string Description { getset; }
    }

    public interface ICategory
    {
        IDetailInformation DetailInformation { getset; }

        INews[] News { getset; }
    }

    public interface INews
    {
        string Tile { getset; }

        string MainContent { getset; }

        DateTime CreatedDate { getset; }

        string Description { getset; }
    }

    public class ListOfCategory
    {
        [JsonProperty("categories")]
        [JsonConverter(typeof(CustomArrayCreationConverter<ICategoryCategory>))]
        public ICategory[] Categories { getset; }
    }

    [JsonObject]
    public class DetailInformation : IDetailInformation
    {
        [JsonProperty("name")]
        public string Name { getset; }

        [JsonProperty("shortName")]
        public string ShortName { getset; }

        [JsonProperty("description")]
        public string Description { getset; }
    }

    [JsonObject]
    public class Category : ICategory
    {
        [JsonProperty("detailInformation")]
        [JsonConverter(typeof(CustomObjectCreationConverter<IDetailInformationDetailInformation>))]
        public IDetailInformation DetailInformation { getset; }

        [JsonProperty("listOfNews")]
        [JsonConverter(typeof(CustomArrayCreationConverter<INewsNews>))]
        public INews[] News { getset; }
    }

    [JsonObject]
    public class News : INews
    {
        [JsonProperty("title")]
        public string Tile { getset; }

        [JsonProperty("mainContent")]
        public string MainContent { getset; }

        [JsonProperty("createdDate")]
        [JsonConverter(typeof(JavaScriptDateTimeConverter))]
        public DateTime CreatedDate { getset; }

        [JsonProperty("description")]
        public string Description { getset; }
    }

Finally, I used it as

var categories = JsonHelper.DeserializeObject<Category>(Result);

Certainly, you must download the piece of JSON Data and store it to Result variable above. Happy your code!

18 Comments

Comments have been disabled for this content.