Skip to main content

Runtime generated objects serialization

If you think in a generic way about all well implemented RESTful APIs you will find a pattern that can be easily described and stored in metadata. Most RESTful API is just a combination of the following elements:

  • Resource location (URL)
  • HTTP method
  • Header information
  • Input parameters (required and optional)
  • Content type
  • Output parameters
  • Business logic description

Today I would like to discuss an interesting problem that I came across recently. Imagine for a second that you need to implement a RESTful API client which uses a combination of metadata which describes API and a user input in order to make a HTTP calls. 

In such a scenario you will quickly realize that for a subset of API calls you will need to develop a custom classes in order to have  them later serialized (to JSON or XML) in runtime so that you can send it via POST or PUT requests. This rises a question. Do I really need to implement N - 1 classes that represent all types that some API(s) expect(s) as a part of HTTP request body?

Well, maybe. In my case I decided to use a more generic approach and leverage a simplicity of standard data formats like JSON. The 'hack' is very simple. From a serialization point of view any class is just a container for properties of specific type - methods and interfaces we can skip as its have nothing to do with serialization. Lets than simplify a class generic description. A class is a collection or key-value pairs. Sounds similar isn't it? Maybe it sounds like JSON format description? This is correct...milestone achieved. 

We already know that we have a key-value pair type of collection. How to describe it from a data structure perspective? Very simple! Actually so simple that we have more than one option available.

We can use the followings:
  • Dictionary<string,object>
  • dynamic type
  • Anonymous types and var 
Other:
  • Approach with List<Tuple<string,object>> does not work! A result JSON has a structure with a property names like Item1, Item2....expected.
[{"Item1":"Name","Item2":"Damian"},{"Item1":"Surname","Item2":"Damian"},{"Item1":"Age","Item2":12},{"Item1":"Books","Item2":["Book 1","Book 2"]}]
  • If you know any other method (even crazy and geeky version) please let me know. Just don't send a one with reflection...
OK. It's time to serialize out classes.

1. By using Dictionary<string, object>

      // Dictionary approach
      Dictionary<stringObject> userDict = new Dictionary<stringobject>();
      userDict.Add("Name""Damian");
      userDict.Add("Surname""Zapart");
      userDict.Add("Age", 12);
      userDict.Add("Books"new List<String> { "Book 1""Book 2" });
 
      JsonConvert.SerializeObject(userDict);

2. By using a dynamic type

       // Dynamic type approach
       dynamic user = new
       {
           Name = "Damian",
           Surname = "Zapart",
           Age = 12,
           Books = new List<String> { "Book 1""Book 2" },
       };
 
       JsonConvert.SerializeObject(user);




3. By using anonymous types

          // Anonymous approach
          var userAnonymous = new
          {
              Name = "Damian",
              Surname = "Zapart",
              Age = 12,
              Books = new List<String> { "Book 1""Book 2" }
          };

And we done! Was a pleasure. Next time will focus on a performance of each solution.

Result JSON.

Popular posts from this blog

Using Hortonworks Hive in .NET

A few months ago I decided to learn a big data. This sounds very complex and of course it is. All these strange names which actually tells nothing to person who is new in these area combined with different way of looking at data storage makes entire topic even more complex. However after reading N blogs and watching many, many tutorials today I finally had a chance to try to write some code. As in last week I managed to setup a Hortonworks distribution of Hadoop today I decided to connect to it from my .NET based application and this is what I will describe in this post. First things first I didn`t setup entire Hortonworks ecosystem from scratch - I`d love to but for now it`s far beyond my knowledge thus I decided to use a sandbox environment provided by Hortonworks. There are multiple different VMs available to download but in my case I`ve choose a Hyper-V. More about setting this environment up you can read here . Picture 1. Up and running sandbox environment. Now whe...

Creating common partial class with Entity Framework

When we use the Entity Framework (EF) in multilayer information systems sometimes we want to extend classes generated by EF by adding some common properties or functions. Such operation can`t be conduct on *.edmx data model so we need to make some improvement in our solution. Let`s begin... Lets assumed that in our soulution we have only three layer (three project): Client console application which has reference to the second layer  - ' ConsoleApplication ' project name Class library project with class interfaces only - ' Interfaces ' project name Class library class implementation and data model referenced to 'Interfaces' project - ' Classes ' project name. Picture 1. Solution structure. Now when we have all solution structure we can focus on data model. In the ' Classes ' project we create a new folder named ' Model ' and inside add new item of ADO.NET Entity Data Model named ' Learning.edmx ' - it may be empty ...

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileSt...