Deserialization of JSON using Json.NET

If you have ever worked with Web APIs, you already know their importance and how much they are used in the world of web services. One of the most important part of the consumption of a Web APIs is the transformation of the response received to a format that is usable for the developer. I usually try to convert the response (a json) to an object, so that it can be used easily by the properties.

Json.NET is a very good JSON framework for .NET which you can use to serialize / deserialize the json.

Here, I am going to show you the deserialization of json to c# objects.

Suppose, you have following json object:

string json = 
@"{
    'id': '101',
    'title': 'Parent Title',
    'child': {
      'childId': '201',
      'childTitle': 'Child Title'
    }  
  }";

To  convert this json, we need to define two classes:

public class Parent
{
  [JsonProperty("id")]
  public int id { get; set; }

  [JsonProperty("title")]
  public string title { get; set; }

  [JsonProperty("child")]
  public Child child { get; set; }
}
public class Child
{
  [JsonProperty("childId")]
  public int childId { get; set; }

  [JsonProperty("childTitle")]
  public string childTitle { get; set; }
}

Now, we can convert the json, like this:

var parent = JsonConvert.DeserializeObject<Parent>(json);

This is a simple case where we have a single parent object with a single child object but there could be other complex cases. Now we will take a look to some of the complex cases.

Array of Parent Objects

If, instead of a single parent object, we have an array of parent objects, each having a single child object, it can be deserialized by changing the call:

var parent = JsonConvert.DeserializeObject<List<Parent>>(json);

Array of Child Objects

Now, if the parent objects in the array also have arrays of child objects, then:

string json = @"[
  {
    'id': '101',
    'title': 'Parent Title 1',
    'child': [{
      'childId': '201',
      'childTitle': 'Child Title 11'
    }]  
  },
  {
    'id': '102',
    'title': 'Parent Title 2',
    'child': [
       {
         'childId': '201',
         'childTitle': 'Child Title 21'
       },
       {
         'childId': '202',
         'childTitle': 'Child Title 22'
       }]  
  }
]";

To handle this case, we need to define the child as a List in the parent object.

So, instead of:

  [JsonProperty("child")]
  public Child child { get; set; }

it should be:

  [JsonProperty("child")]
  public List<Child> child { get; set; }

Handle both a single item and an array

Now, consider the situation where some of the objects have child arrays while others have a child object. This case cannot be handled by simply structuring your parent or child class, rather than that, you need to override JsonConverter class and need to define the child list using it.

Have a look at the json first:

string json = @"[
  {
    'id': '101',
    'title': 'Parent Title 1',
    'child': {
      'childId': '201',
      'childTitle': 'Child Title 11'
    }
  },
  {
    'id': '102',
    'title': 'Parent Title 2',
    'child': [
       {
         'childId': '201',
         'childTitle': 'Child Title 21'
       },
       {
         'childId': '202',
         'childTitle': 'Child Title 22'
       }]  
  }
]";

Now, you need to define child list like this:

[JsonProperty("children")]
[JsonConverter(typeof(ArrayOrObjectConverter<Child>))]
public List<Child> children { get; set; }

And you need to override JsonConverter class like this:

public class ArrayOrObjectConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }
    public override object ReadJson(JsonReader reader, Type objectType,
      object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }
    public override bool CanWrite
    {
        get { return false; }
    }
    public override void WriteJson(JsonWriter writer, object value,
      JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

In this way, you can convert both the object or an array of objects. However, the parent object will always contain a List of objects having one or more child objects.

 

Dependency Injection using Castle Windsor

Dependency Injection (a design pattern) is a very useful concept and a really cool way of programming. It allows the developer to focus on the core responsibility of the class, forgetting about the implementation of dependencies because the caller is responsible to inject the dependencies.

Let’s clarify it with an example. Let’s say you have a Migrator class which reads data from the source, transform it and write it to the target data store.

public class Migrator
{
  private Source source;
  private Target target;

  public Migrator()
  {
    source = new Source();
    target = new Target();
  }

 public void Migrate()
 {
    var data = source.ReadData();
    //Perform data transformation here
    target.WriteData(data);
 }
}

In the above example, source and target objects are instantiated inside the constructor. Now, if the implementation of any of these dependencies changes, this class will also need to be updated accordingly. For example, if the Source class constructor changes to accept an object of IStream, then the constructor of the Migrator class will also need to be updated.

  public Migrator()
  {
    Stream stream = new FileStream(...);
    source = new Source(stream);
    target = new Target();
  }

It is a very simple example. There could be more complex situations. So, to avoid these problems, we can use DI like this:

public class Migrator
{
  private ISource Source;
  private ITarget Target;

  public Migrator(ISource source, ITarget target)
  {
    Source = source;
    Target = target;
  }

 public bool Migrate()
 {
    var data = Source.ReadData();
    //Perform data transformation and write
    Target.WriteData(data);
    return true;
 }
}

Here, instead of creating dependencies itself, the Migrator class is expecting to receive them in the constructor by the caller. So now, it is caller’s responsibility to write Source and Target classes implementing ISource and ITarget interfaces and pass them in the constructor. In this way, the Migrator class is much more flexible too as it can use any Source and Target provided by the caller for the migration.

  static void Main(string[] args)
  {
    Stream stream = new FileStream(...);
    ISource source = new MyNewSource(stream);
    ITarget target = new MyNewTarget();
    var migrator = new Migrator(source, target);
    migrator.Migrate();
  }

This also makes the testing of the Migrator class easier as the caller can use any type of source and target implementation.

This is a basic idea of what dependency injection is. Now, to get an idea how Castle Windsor can help us in DI, we will create a Visual Studio Project.

Castle Windsor is a IoC (inversion of control) framework. To use it, you just need to add its reference using Nuget. So create a console application in Visual Studio and add a reference to Castle Windsor.

untitled

Now, you will change the caller code like below:

static void Main(string[] args)
{
   IWindsorContainer container = new WindsorContainer();
   container.Install(FromAssembly.This());
   var migrator = container.Resolve<Migrator>();
   migrator.Migrate();
   container.Dispose();
}

Here, we have created a container and added an installer. Now, to create an object of Migrator class, we just need to call container.Resolve<Migrator> and it will take care of the creation of all the dependencies and the Migrator class.

Castle Windsor uses the installer to identify the object and its dependencies. We need to define the installer like this:

public class MyWindsorInstaller: IWindsorInstaller
{
   public void Install(IWindsorContainer container, IConfigurationStore store)
   {
      container.Register(Component.For<Migrator>());
      container.Register(Component.For<ISource>()
               .ImplementedBy<Source>());
      container.Register(Component.For<ITarget>()
               .ImplementedBy<Target>());
   }
}

Here, we are only registering class Migrator and we are very specific for the dependencies. However, we can also do the same as below and it will resolve components automatically.

public void Install(IWindsorContainer container, IConfigurationStore store)
   {
      container.Register(Classes.FromAssemblyInThisApplication().Pick()
         .WithServiceAllInterfaces()
         .Configure(conf => conf.Named(conf.Implementation.Name))
         .LifestylePerThread());
   }

Now, the Castle Windsor will take care of the creation of all the dependencies and passing them to the Migrator class. So now, you don’t need to worry about it even if the implementation of any of the dependencies or the Migrator class changes.

This is a very basic example of Dependency Injection and how to use Castle Windsor for DI. This framework is much more powerful and has lots of configuration options.

More Information:

Windsor | Castle Project

Dependency injection

Inversion of control