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

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

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

Using Newtonsoft serializer in CosmosDB client

Problem In some scenarios engineers might want to use a custom JSON serializer for documents stored in CosmosDB.  Solution In CosmosDBV3 .NET Core API, when creating an instance of  CosmosClient one of optional setting in  CosmosClientOptions is to specify an instance of a Serializer . This serializer must be JSON based and be of  CosmosSerializer type. This means that if a custom serializer is needed this should inherit from CosmosSerializer abstract class and override its two methods for serializing and deserializing of an object. The challenge is that both methods from  CosmosSerializer are stream based and therefore might be not as easy to implement as engineers used to assume - still not super complex.  For demonstration purpose as or my custom serializer I'm going to use Netwonsoft.JSON library. Firstly a new type is needed and this must inherit from  CosmosSerializer.  using  Microsoft.Azure.Cosmos; using  Newtonsoft.Json; usin...