She used this one neat trick to model JSON as classes in C#, and her audience was stunned!

I recently presented my talk Testing RESTful Web Services for the first time at the QL Technology Conference in Detroit. In this talk, I cover why we should test web services, and how to test RESTful web services both with tools like Postman, and C# and NUnit.

I was not prepared for, mid-demo, resounding applause from the audience. I was demoing a cool trick I learned from a teammate, and apparently it was new magic to the audience. Awesome! So I decided to blog about it, to spread the word of this fancy magic and help everyone save time when testing RESTful web services within Visual Studio.

What was that magic? It’s the ability to take a JSON response and quickly turn it into a class – a super fast way to model JSON responses!

applause

Huzzah!

If you already know how to do it, awesome! Spread the word!

What you need:

  • a JSON response to copy/paste
  • Visual Studio, with a solution loaded (we’ll use C#, not sure how it works with other languages)

I’ll use the same examples from my talk – it uses the gitter API (http://gitter.im).

First, create a new class file in your project:

  • Right-click in Solution Explorer where you want the file to go
  • Select Add -> Class
  • Type a name and click Add

Then, paste the JSON as classes!

  • Copy the JSON you want to model as a class
  • Inside the class file in Visual Studio, put your cursor inside the namespace
  • Choose Edit -> Paste Special -> Paste JSON As Classes
  • Much rejoicing!

You’ll need to clean up the class a bit, but it will definitely save you time!ClassesAndJson.png

I hope you’re able to use this neat trick to help you in your testing of web services!

You will want to choose your JSON responses for modeling carefully – make sure it has all of the potential properties! Otherwise, down the road when you’re deserializing, you’ll hit a failure because the JSON will have an extra property that your class is missing.

Any other neat tricks you can share?

Advertisements

Posted on October 12, 2016, in Coding Stuff, Testing. Bookmark the permalink. 1 Comment.

  1. /slowclap/
    I have not seen or used this before. Thanks for sharing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: