Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Monday, January 16, 2017

C# WebClient Parsing JSON Array

This is a snippet of code that calls a RESTful web service and parses the JSON result.  The JSON payload is a list of objects.  The solution uses the .NET class DataContractJsonSerializer and an annotated DataContract.

This blog post expands on an article "Parsing REST Services" on the Microsoft site.

Setup

Create a Project of type Console App (.NET Framework).  Add the System.Runtime.Serialization assembly to the References.

Service

This service can be tested with the URL https://www.bekwam.net/data/customers.json.  This is actually a text file hosted on a web service.

The result of calling the fake service is the following.

[
{"id": 1, "firstName": "George", "lastName" : "Washington"},
{"id": 2,"firstName": "Abe", "lastName": "Lincoln"},
{"id": 3, "firstName": "Franklin", "lastName": "Roosevelt"}
]

Code

The following code is added to the Program.cs file.  The Customer class is marked with DataContract attributes.  This provides information to the serializer about how to unpack the JSON text result.

The WebRequest class is used to issue the HTTP call.  The returned HttpWebResponse object status is checked.  If OK, the serializer is passed the response.

namespace WebClientApp
{
    [DataContract]
    public class Customer
    {
        [DataMember(Name = "firstName")]
        public string FirstName { get; set; }
        [DataMember(Name = "lastName")]
        public string LastName { get; set; }
        [DataMember(Name = "id")]
        public int Id { get; set; }
        [DataMember(Name = "resourceSets")]
        public ResourceSet[] ResourceSets { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {

            if (args == null || args.Length == 0)
            {
                throw new ApplicationException(
                 "Specify the URI of the resource to retrieve."
                );
            }

            Console.WriteLine("Calling " + args[0]);

            HttpWebRequest request = WebRequest.Create(args[0]) as HttpWebRequest;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    response.StatusCode,
                    response.StatusDescription));
                DataContractJsonSerializer jsonSerializer = 
                  new DataContractJsonSerializer(typeof(List<Customer>));
                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                List<Customer> jsonResponse = objResponse as List<Customer>;

                foreach (var c in jsonResponse) {
                    Console.WriteLine(String.Format("id={0}, firstName={1}, lastName={2}",
                        c.Id,
                        c.FirstName,
                        c.LastName)
                        );
                }
            }        

            Console.ReadLine();
        }
    }
}

By adding the single Assembly Reference, you can use a DataContractJsonSerializer and marked-up class to parse JSON from a RESTful web service call.  This example pulled down a JSON array of Customers and unpacked them into a List of Customer objects using the ReadObject method.

No comments:

Post a Comment