Json.NET is an open source project by James Newton-King. I have used this framework in my project in the past months and I am really enjoying its simplicity and power.
I mainly use this framework to convert objects or instances to an Json string or XML string, vice visa. The framework provides many classes but I only use a very small set of them. For my purpose, what I need its classes related serialization and de-serialization. Based on my practice and experience, I wrote a wrapper class with several methods for my usages. I like to wrapper Json.NET framework is based on the following reasons:
- To hide Json.NET from its clients or users. As a result, users will not see Json.NET or need to add reference to Json.NET. All my projects need is to reference to my wrapper class.
- To provide a clean and simplified set of methods for my usages. This relates to the previous reason. Users will not see rich and complicated Json.NET framework.
Basicaly, I use Json.NET for the following usages:
- Configuration file for applications; and
- Simplify my overrides of ToString() methods for classes.
Microsoft .Net provides framework for configuration. By default, you can have configuration in XML files like app.config or web.config. The problem is that the configuration file is very restrict in sense of its structure. You have to follow its XML structure to put your settings there. The most annoying thing is that when you save some settings, whatever comments you used as reference will be gone.
I like to write configuration in any way I would like. With Json.NET, this is possible. The configuration file can be either Json string or XML string in a file. Both of them can be easily converted or mapped to an instance of a class, called as configuration class. For example, I load my XML configuration file by using TextReader class as XML string. Then I convert it a Json string. From Json string, I use Json.NET to deserialize it to an instance of my confiugration class.
In case I need to make changes of some configuration settings, I use XMLDocument and Parser classes to make changes in XML string and leave other parts not touched. Finally I save the XML string to my configuration file.
For my purpose of overriding ToString() methods, before Json.NET I had to write hard codes to format property values to a string. This is really inconvenient. If I make changes of property names, I have to remember to change my ToString(); otherwise, my ToString() is unsynched. I do need to override ToString() when I need to debug my codes into a log file. With Json.NET, I can simply to serialize instance of
this
to a Json string. The serialization takes care of all the properties in a nice Json style. This is really very handy!I'll continue to discuss my wrapper class in detail in my next blog.