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!
Published Thursday, August 26, 2010 11:50 AM by thangchung
Filed under: , ,

Comments

# re: Customizing the Converter for Json.NET

Thursday, August 26, 2010 10:59 AM by Webdiyer

How about DataContractJsonSerializer?

# re: Customizing the Converter for Json.NET

Sunday, August 29, 2010 10:46 PM by thangchung

It's good. And it come from .NET 3.0 or later and permitted to render the clearly JSON data than the XmlSerializer from older version. But when I read this performance comparison from James at james.newtonking.com/.../net-serialization-performance-comparison.aspx. I considered to use the Json.net.

# re: Customizing the Converter for Json.NET

Tuesday, September 7, 2010 11:59 AM by MrTumi

Nice post! I would like to invite you to join in the new community for world developers and vietnamese developers http://geeksship.com

Geeksship is a community support multi-culture topics, history version and many more..

Thanks!

# re: Customizing the Converter for Json.NET

Saturday, October 2, 2010 5:22 AM by Moi

Excellent, thanks a lot.

# re: Customizing the Converter for Json.NET

Friday, April 8, 2011 11:59 PM by new era hats

when we visit this new era store online, we see so many new era hats cheap there, and new fashion new era hats wholesale price. just to do new era caps wholesale and wholesale new era hats with them.

# re: Customizing the Converter for Json.NET

Saturday, October 29, 2011 7:20 AM by xzVZuAmfAxuU

sBuDYv Interesting. We are waiting for new messages on the same topic!!...

# re: Customizing the Converter for Json.NET

Saturday, November 5, 2011 2:53 PM by pRzbepiNxJSiTCrk

Q7bd0q I do`t see a feedback or the other coordinates from the blog administration!....

# re: Customizing the Converter for Json.NET

Tuesday, December 27, 2011 10:25 PM by PcUfInGHbkDmwvDELTK

RTUwzT I subscribed to RSS, but for some reason, the messages are written in the form of some hieroglyph (How  can it be corrected?!....

# re: Customizing the Converter for Json.NET

Saturday, March 31, 2012 7:44 AM by Android apps developer

I look forward to more updates and will be returning back..

# re: Customizing the Converter for Json.NET

Thursday, April 5, 2012 11:50 AM by vVVwgifuMb

a9BFcf Say, you got a nice blog article.Thanks Again. Keep writing.

# re: Customizing the Converter for Json.NET

Saturday, April 14, 2012 5:40 AM by GbzklUpbyfTReYFuCIO

vfhAxD Thanks so much for the article. Will read on...

# re: Customizing the Converter for Json.NET

Monday, July 9, 2012 9:37 AM by ARawGdlwQOqIQZ

Axuhwr I am so grateful for your article post. Great.

# re: Customizing the Converter for Json.NET

Saturday, September 8, 2012 9:17 AM by DTcIALilcGaD

W89PC6 I am so grateful for your blog article. Awesome.

# re: Customizing the Converter for Json.NET

Sunday, November 4, 2012 9:55 PM by hIJTESCQplVSErVrAX

xyqmYe Looking forward to reading more. Great article.Much thanks again. Will read on...

# re: Customizing the Converter for Json.NET

Sunday, November 25, 2012 9:20 AM by hbdsDyhdOX

s4Xzu4 Fantastic article post.Much thanks again. Great.

# re: Customizing the Converter for Json.NET

Wednesday, December 19, 2012 3:07 AM by lcbdiaxyfim@hotmail.com

I have been browsing online more than 3 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my view, if

# re: Customizing the Converter for Json.NET

Saturday, December 22, 2012 2:19 AM by Schwab

What a data of un-ambiguity and preserveness of valuable experience about unexpected

emotions.

# re: Customizing the Converter for Json.NET

Saturday, December 22, 2012 2:19 AM by pdMXKhwzCQLdXSkR

1Er8Sp Say, you got a nice article. Awesome.

# re: Customizing the Converter for Json.NET

Thursday, February 28, 2013 2:12 PM by fGQjTOcxktFRBaVax

aptNTf Very good article post.Thanks Again. Much obliged.