Visual Studio Tips and tricks: Paste as JSON

 
 
  • Gérald Barré

If you often work with JSON documents, you may have created classes to map the content of the JSON document to a .NET class. Then, Json.NET or the new System.Text.Json allows to serialize a class to a JSON string or to deserialize a JSON string to a .NET class.

Writing mapping classes is annoying and error-prone. Instead of writing them yourself, Visual Studio can generate them using 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; }
}

Very handy 😃

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?Buy Me A Coffee💖 Sponsor on GitHub