simple json c# correct way to deserialize dictionary

We are using RESTSharpLibrary to work with third party REST based API
Which by default support XML and JSON deserialization. but their documentation for Deserialization is covered with a limited simple example. which was not sufficient to help us consume Complex JSON output.

We are using http://json2csharp.com/ to convert JSON string to C# class.
Which works perfectly when JSON string is in a simple structure. but when it comes to Deserialize to JSON to Dictionary<string, class> then class generated using json2csharp.com fails.

For example:
Consider following complex JSON response which requires Dictionary<string, class>.

JSON :

 "response":{
      "1007":{
         "total":{
            "inStock":10,
            "onHand":9,
            "allocated":1
         }
      },
      "1008":{
         "total":{
            "inStock":0,
            "onHand":0,
            "allocated":0
         }
      }
   }
}

Output after converting JSON to C# class using converter tool:

public class Total
{
    public int inStock { get; set; }
    public int onHand { get; set; }
    public int allocated { get; set; }
}

public class __invalid_type__1007
{
    public Total total { get; set; }
}

public class Total2
{
    public int inStock { get; set; }
    public int onHand { get; set; }
    public int allocated { get; set; }
}

public class __invalid_type__1008
{
    public Total2 total { get; set; }
}

public class Response
{
    public __invalid_type__1007 __invalid_name__1007 { get; set; }
    public __invalid_type__1008 __invalid_name__1008 { get; set; }
}

public class RootObject
{
    public Response response { get; set; }
}

Wrong way to put Dictionary:

.....
public class Response
{
 public Dictionary<string, Product> products { get; set; }
}

public class RootObject
{
 public Response response { get; set; }
}
.....

The right way to put Dictionary:

 public class RootObject
 {
 //We need following Minor Modified to make class correctly Deserialize:
 public Dictionary<string, Product> response { get; set; }

}
 public class Product
 {
 public Total total { get; set; }

}
 public class Total
 {
 public int inStock { get; set; }
 public int onHand { get; set; }
 public int allocated { get; set; }
 }

I hope this article saves time for you.

By | 2017-01-03T16:28:07+00:00 April 11th, 2014|Asp.Net, Tips and Tricks, Web Service|