Visual Studio Tips and tricks: Paste as JSON

 
 
  • Gérald Barré

If you often work with JSON documents, you may have written classes to map JSON content to .NET types. Libraries like Json.NET or System.Text.Json can then serialize and deserialize those classes to and from JSON.

Writing these mapping classes by hand is tedious and error-prone. Instead, Visual Studio can generate them automatically from a sample JSON string.

  1. Copy a JSON string to the clipboard
  2. Use Paste JSON as classes

Paste JSON as classes in Visual StudioPaste JSON as classes in Visual Studio

Let's try with the following JSON document:

JSON
{
  "markers": [
    {
      "name": "Rixos The Palm Dubai",
      "position": [25.1212, 55.1535],
    },
    {
      "name": "Shangri-La Hotel",
      "location": [25.2084, 55.2719]
    },
    {
      "name": "Grand Hyatt",
      "location": [25.2285, 55.3273]
    }
  ]
}

Visual Studio generates the following code:

C#
public class Rootobject
{
    public Marker[] markers { get; set; }
}

public class Marker
{
    public string name { get; set; }
    public float[] position { get; set; }
    public float[] location { get; set; }
}

This feature is a real time-saver when working with JSON data.

This post is part of the series 'Visual Studio Tips and Tricks'. Be sure to check out the rest of the blog posts of the series!

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?