JSON and XML to C# classes in Visual Studio

Although this feature is available for years in Visual Studio, I only recently discovered this gem that allows rapid generation of C# classes from either JSON or XML.

Here is how it works:

  1. Copy the JSON or XML code to the clipboard.
  2. In Visual Studio, go to Edit > Past Special and chose either Paste JSON as classes or Paste XML as classes.

However, this feature is only available if you have the ASP.NET and web development workload installed.

JSON to classes

To check how this feature works and how it compares with other alternatives I picked a couple random JSON examples. The first one is from the responses of the Translator Text API (that you can find here):

Special pasting in Visual Studio produces the following classes:

A couple of remarks related to this:

  • The Rootobject is not actually present in JSON, and you cannot deserialized the sample JSON to an instance of this class, but rather to a Class1[].
  • The score is a floating point number and the type used here is float, although I would have expected double.

I compared this result with the output of several online similar utilities.

JSON Utils produces the following result:

QuickType has the following result:

Notice that, unlike the Visual Studio functionality where all the options are hard-coded, these online utilies allow you to set various options such as whether property attributes should be generated, whether to use T[] or List<T> and others. The QuickType app supports a larger number of features, although you must be authenticated to toggle them.

The results from these are pretty similar. Neither of them generated a root object like Visual Studio did. The first application used double for the numerical type of 1.0, while the second used long. When I changed the value from 1.0 to 1.2, QuickType also used double.

Another example that I tried was from https://json.org/example.html:

The result of converting this to classes was mostly identical in all three cases (Visual Studio, JSON Utils, and QuickType), with the exeption of the casing and the type for the numerical values (QuickType used long instead of int).

XML to classes

For testing the XML to classes functionalities I used the XML equivalent of the last JSON example, which looks as follows:

Visual Studio converted this to the following C# code:

By contrast, the online utility at https://xmltocsharp.azurewebsites.net/ produces the following output from the same XML document:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.