Paste JSON as Classes

Posted by jineesh uvantavida on Thursday, November 10, 2022 Under: Tips & Ideas.
Paste JSON as Classes

When working with APIs we often send a request and receive JSON data. Using C#, we need to transform the data into an object tree. That’s where what I’m going to show you is a game-changer.

First, let’s assume we receive the following JSON data from an API:
{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "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"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

Now, let’s copy the JSON data into the clipboard, and in the Edit menu, select the Paste special menu and click on Paste JSON as classes.
public class Rootobject
{
    public string SquadName { get; set; }
    public string HomeTown { get; set; }
    public int Formed { get; set; }
    public string SecretBase { get; set; }
    public bool Active { get; set; }
    public Member[] Members { get; set; }
}
public class Member
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string SecretIdentity { get; set; }
    public string[] Powers { get; set; }
}

As you can see, Visual Studio generated a class structure matching the JSON data. Imagine how much time and tedious typing work you’ll save if you have a big data structure. Visual Studio also can do the same for XML data.

In : Tips & Ideas. 


Tags: paste json as classes visual studio creating model from classes 

Translate This Page

 


Make a free website with Yola