How To Turn an API Response Into a C# Class?

Table of contents

Why?

When using APIs, you rarely need your response object to remain a string. If you need to access its properties, convert it to a view model or manipulate it any other way, you have to convert it to a C# object. When dealing with an operation like this in the world of programming, we call it a Deserialization. You’ll often find an example of the response object in the API documentation, but that’s not always the case. Sometimes, you just have to rely on the JSON response you get from the API to create your C# class. Since I’ve been through the process many times, I’ll try outlining a few steps how to get that done quickly and painlessly. If you already have the raw JSON response available, you can move on to step 3.

Get The Raw API Response

Consider this endpoint. It’s an example API response from this website with dummy endpoints.

In C#, we can easily implement a method that grabs that data on a simple out of the box Console Application like so (by the way… try to never use .Result on asynchronous calls. Instead, await the call. The last thing I want to do is to promote bad practices!):

    class Program
    {
        /// <summary>
        /// http://www.dummy.restapiexample.com/
        /// </summary>
        /// 
        static void Main(string[] args)
        {
            using (var http = new HttpClient())
            {
                var endpoint = "http://dummy.restapiexample.com/api/v1/employees";
                var result = http.GetAsync(endpoint).Result;
                var json = result.Content.ReadAsStringAsync().Result;
                Console.WriteLine(json);
            }
        }
    }

If you run this code, you should see the response in written to the Console output.

Convert Into C# Class

You can now copy that JSON output from the previous step (or your own) and navigate to JSON2CSharp.com. A very handy tool for this kind of scenarios. Paste your JSON string in the JSON box on the left and press Convert. Voila!

Using json2csharp.com to convert objects
Using json2csharp.com to convert objects

We have to remember that sometimes, the tool can get confused about the data type and assign an object, or another wrong type. In those cases, we have to look at that property and decide which data type should we use. Generally, a string is always a good choice if we’re dealing with primitive types. In this example, there’s one nested class that the tool called Datum, feel free to rename that class name (I’ve renamed it to Data). What matters here is a property name and not the class name, but you want to keep them the same, or very similar, so it’s not confusing.

One other thing to notice, is that the main object is always named Root. This will be the name of the root class, so in this case I’d rename it to something like GetEmployeesResponse.

The final result looks like this for me:

    class GetEmployeesResponse
    {
        public string status { get; set; }
        public List data { get; set; }
        public string message { get; set; }

        public class Data
        {
            public int id { get; set; }
            public string employee_name { get; set; }
            public int employee_salary { get; set; }
            public int employee_age { get; set; }
            public string profile_image { get; set; }
        }
    }

The names of the class properties must match the JSON string field names (case-sensitive), but there’s a way to use another name for your C# class properties. Using JsonProperty attribute (requires Netwonsoft.Json library). The below will work just fine when deserializing the status field:

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

Use Your New Class

Once you have your new class, using it to deserialize the response object is as easy as adding the following line to your code using JsonConvert (requires Netwonsoft.Json library):

var obj = JsonConvert.DeserializeObject<GetEmployeesResponse>(json);

Deserialization in code using Newtonsoft.Json library
Deserialization in code using Newtonsoft.Json library

Conclusion

Create an API response object is as simple as copy & paste with very little configuration needed. You now have access to each property of the API response json string, despite of the number of nested objects and collections – it’s all handled for you in terms of deserialization.

A good practice is to keep that API response up to date with the API docs and creating a view model for it if you’d like to strip out properties that you don’t need, or add any custom fields to it.

Leave a Reply