During the development, often, we require generating classes from JSON objects or XML objects, typically when we need a data to object mapping. In many instances, you may run for manually writing the members of the classes based on the property names coming from your JSON or based on XML attributes. However, there is a very interesting, but a little-overlooked feature, of Visual Studio, using which you can generate the classes directly by pasting the JSON or XML.
Using “Paste JSON As Classes” or “Paste XML As Classes”, Visual Studio and automatically have your classes generated.
Let’s have a quick look at an example. Consider you have following JSON.
{ "id": 1, "name": "Product1", "price": 12.50, "tags": ["tag1", "tag2"] }
Now, You want to have a class for this JSON. Instead going through the process of manual creation, do the following:
- Create an empty class in Visual Studio
- From main menu Edit -> Paste Special -> Paste JSON As Classes
With that, you will find you have a transformed class created from the selected JSON, as shown in the above image.
Similarly, this is going to be same for XML Files. You can use Paste XML As Classes for generating the class from an XML File.
Consider the following sample XML file
<book id="1"> <author>Book Author</author> <title>Book Title</title> <price>49.95</price> <description>Book description</description> </book>
Now, you can generate the complete class by selecting “Paste XML As Classes”
This is not a new feature of Visual Studio, it is there since long. Give it a try, if you are not using it.
With this feature you can make your classes simpler, faster, and more interesting. Isn’t it!
Hope this helps!
Pingback: Dew Drop - November 9, 2017 (#2600) - Morning Dew
Very good tip I was not aware.Thank you for sharing.
NIce one !
Pingback: Compelling Sunday – 17 Posts on Programming and QA
The example would be more impression if the JSON/Xml had more than one level , requiring VS to generate multiple classes
{
“id”: 1,
“name”: “Product1”,
“price”: 12.50,
“tags”: [“tag1”, “tag2”],
“someObject”: {“id”: “1a”, “value”: 1234}
}
public class Rootobject
{
public int id { get; set; }
public string name { get; set; }
public float price { get; set; }
public string[] tags { get; set; }
public Someobject someObject { get; set; }
}
public class Someobject
{
public string id { get; set; }
public int value { get; set; }
}
I have “Paste XML as classes” but no “Paste JSON as classes” ? Any ideas? I DO have ASP.NET installed btw.
@Jim Delaney
It’s not that intuitive, but if you only see Paste As XML Classes, Simply Create a new Class File, then go to Edit -> Paste Special , then Paste JSON as classes will become visible.
I don’t know why it’s not available on menu otherwise