Overview

If you work JSON documents, I’m sure you’ve probably had to create a class file from a JSON string. Doing this manually can be a real pain in the proverbial, especially if you are working with a large JSON document. It can also be very error-prone. Therefore it’s best to automate this conversion.

In this post I’ll show you how to automatically generate a class file from a JSON string using a little known feature built into Visual Studio.

Visual Studio Icon

Solution

Visual Studio has a little known built-in feature that can automatically generate a class for you from a JSON string.

Here’s how to use it:

  1. Create an empty class where you want to insert the auto-generated code.
  2. Copy the JSON string into the system clipboard
  3. Click EDIT > PASTE SPECIAL > PASTE JSON AS CLASSES.
Paste JSON as Class

Demonstration

Lets say we are working with the following JSON string:

[
  {
    "name": "Molecule Man",
    "age": 29,
    "secretIdentity": "Dan Jukes",
    "powers": [
      "Radiation resistance",
      "Turning tiny",
      "Radiation blast"
    ]
  },
  {
    "name": "Madame Uppercut",
    "age": 39,
    "secretIdentity": "Jane Wilson",
    "powers": [
      "Million tonne punch",
      "Damage resistance",
      "Superhuman reflexes"
    ]
  }
]

Visual Studio will generate the following code. Yep, it’s that easy!

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public string name { get; set; }
    public int age { get; set; }
    public string secretIdentity { get; set; }
    public string[] powers { get; set; }
}

Final Thoughts

Well I hope this quick tip has helped you out. If you have found another way to convert a JSON string to a class file, feel free to share it in the comments below.

Happy coding 🙂

Shane Bartholomeusz