Tuesday, February 18, 2014

Using RestSharp to Deserialize JSON Simple Examples


RestSharp is a .NET REST client that can be downloaded and used to easily serialize and deserialize both XML and JSON.  If necessary, it will used fuzzy element name matching to map from the original JSON object to C# so that if an exact property name match isn't found it will use the following precedence to deserialize the data.


  1. Exact property name match (e.g. LastName -> LastName)
  2. Camel-cased version of the property name (e.g. LastName -> lastName)
  3. Lower-cased version of the property name (e.g. LastName -> lastname)
  4. Lower-cased version of "underscored" name (e.g. Last_Name -> last_name)


Using Xamarin Studio, I've included RestSharp from the component store in my C# project.  Here are a few simple examples of how to deserialize JSON into C#.

A Simple Dictionary Key Value such as {"Count":234}
// Create a new RestClient and RestRequest

            var client = new RestClient("http://www.atavisticsoftware.com/");
            var request = new RestRequest ("demo/jsondbcount.php",Method.GET);
// ask for the response to be in JSON syntax
            request.RequestFormat = DataFormat.Json

//send the request to the web service and store the response when it comes back
            var response = client.Execute (request);
// The next line of code will only run after the response has been received
// Create a new Deserializer to be able to parse the JSON object
            RestSharp.Deserializers.JsonDeserializer deserial= new JsonDeserializer();
//To deserialize into a simple variable, use the <Dictionary<string, string>> type
            var JSONObj = deserial.Deserialize<Dictionary<string, string>>(response);              int rowCount =  JSONObj["Count"]; //rowCount will be 234 based on the example {"Count":234}





To deserialize an object such as {"FirstName":"Eileen","LastName":"Dover"}
    public class People 
    {
        public string FirstName { get; set; }
        public string LastName { get; set;}
     }
. . . // (same as first example)
//To deserialize into an object, change the deserialize code to use the <Class> type
//Fuzzy matching is used to map the properties from the JSON object to the C# object properties
People people =  deserial.Deserialize<People> (response);  
//people.FirstName will now be "Eileen"  people.LastName will now be "Dover"

A collection of objects will come in array format such as:


[{"FirstName":"Eileen","LastName":"Dover"},{"FirstName":"Dan","LastName":"Druff"},{"FirstName":"Anita","LastName":"Drink"}]

    public class People 
    {
        public string FirstName { get; set; }
        public string LastName { get; set;}
     }

   public List<People> peopleList;
. . . // (same as first example)
//Change the deserialize code to type <List<Class>>
   peopleList = deserial.Deserialize<List<People>>(response);
//The list of People objects will be populated and the property names matched

In the above examples, the deserialization happens synchronously, so that the application will wait until a response is received before continuing.  RestSharp can also create asynchronous processing so that the application will continue execution without having received a response, but will handle the response from the web service when it arrives without holding up execution of other program logic.  This is especially useful to avoid blocking the UI thread in a mobile app while waiting for the web service and run the risk that the OS will terminate your application.

To make the above example run asynchronously, change the original client.Execute to the following:    
                              
                          . . . // (same as first example)

  client.ExecuteAsync (request, response => {

                RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
 
                peopleList = deserial.Deserialize<List<People>>(response);

            });



//The list of People objects will be populated when the response is finally received from the web service, but code immediately following this will run right away and not be held up waiting for the response

11 comments:

  1. hi can i have the code for the files :
    http://www.atavisticsoftware.com/demo/jsondbcount.php
    http://www.atavisticsoftware.com/demo/index.php

    ReplyDelete
  2. Very good examples.

    Thanks for much.

    ReplyDelete
  3. Thanks! Good examples are in short supply. I scrolled through yours and found exactly what I needed about deserializing a list of objects.

    ReplyDelete
  4. Thanks for sharing this article... Good read

    ReplyDelete
  5. Thanks for sample. It is much easier than I thought! I learned a bit more C# too.

    ReplyDelete
  6. How would you get the "value" array from http://services.odata.org/v3/northwind/northwind.svc/Customers ?

    ReplyDelete
  7. Thank you so much. it was really helpful to me.

    ReplyDelete
  8. This is terrific and worked beautifully! I have a response that is nested like this:
    {
    "id": 91,
    "name": "somename",
    "inactiveFlag": false,
    "systemFlag": false,
    "_info": {
    "lastUpdated": "2017-11-24T21:01:59Z",
    "updatedBy": "someone",
    "questions_href": "a long string here"
    }
    }

    The top level items are deserializing fine using your assistance above, but I am not getting the "updatedBy" and "questions_href" values. Any ideas. Thank you again!!!

    ReplyDelete