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

Persisting Enum in database with Entity Framework

Problem statement We all want to write clean code and follow best coding practices. This all engineers 'North Star' goal which in many cases can not be easily achievable because of many potential difficulties with converting our ideas/good practices into working solutions.  One of an example I recently came across was about using ASP.NET Core and Entity Framework 5 to store Enum values in a relational database (like Azure SQL). Why is this a problem you might ask... and my answer here is that you want to work with Enum types in your code but persist an integer in your databases. You can think about in that way. Why we use data types at all when everything could be just a string which is getting converted into a desirable type when needed. This 'all-string' approach is of course a huge anti-pattern and a bad practice for many reasons with few being: degraded performance, increased storage space, increased code duplication.  Pre-requirements 1. Status enum type definition...

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

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