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

# Customizing the Converter for Json.NET

Thursday, August 26, 2010 12:15 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# Customizing the Converter for Json.NET - Context is King

Thursday, August 26, 2010 4:17 AM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# 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.

# Customizing the Converter for Json.NET

Monday, August 30, 2010 11:39 PM by WebDevVote.com

You are voted (great) - Trackback from WebDevVote.com

# re: Customizing the Converter for Json.NET

Tuesday, September 07, 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!

# Google API for .NET architecture (Part 1)

Sunday, September 12, 2010 2:17 PM by Context is King

Today, I have just released a OSS with named is Gapi4net library at codeplex. This is a wrapper some

# re: Customizing the Converter for Json.NET

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

Excellent, thanks a lot.

# re: Customizing the Converter for Json.NET

Friday, April 08, 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

Monday, August 29, 2011 10:19 PM by echo

www.lpearls.com/.../index.html

# re: Customizing the Converter for Json.NET

Friday, October 07, 2011 4:29 AM by wholesale nike air max

We are pleased to inform you that we have just marketed our newly-developed. You will be interested to hear that we have just marketed our new product.We are pleased to get in touch with you for the supply of.

# 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 05, 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 05, 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 09, 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 08, 2012 9:17 AM by DTcIALilcGaD

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

# re: Customizing the Converter for Json.NET

Thursday, September 20, 2012 12:15 PM by bookmarking service

JzbK7w Really informative article.Thanks Again. Really Great.

# re: Customizing the Converter for Json.NET

Thursday, October 18, 2012 4:23 AM by R4i Gold 3DS vente

Great post, you have pointed out some superb points R4i(http://www.ir4ds.org/) , I besides conceive this s a very superb website.

# re: Customizing the Converter for Json.NET

Sunday, November 04, 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

Saturday, January 05, 2013 8:44 PM by skoilwqlg@live.com

I simply want to tell you that I am just very new to blogging and site-building and honestly loved your web page. More than likely I’m want to bookmark your

# Inheritance and Reference in Json.NET - nonocast

Friday, February 01, 2013 12:43 PM by Inheritance and Reference in Json.NET - nonocast

Pingback from  Inheritance and Reference in Json.NET - nonocast

# 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.

Leave a Comment

(required) 
(required) 
(optional)
(required)