Creating a DTO class from a JSON string in Visual Studio

If you’ve got back some JSON from a REST API you’ll likely be wanting to use Newtonsoft or System.Text.Json (.NET Core 3.0) to deserialize that JSON into a .NET DTO class to make working with it easier.

To create the DTO you can

1 – Manually examine the JSON and manually create the C# class or
2 – Use an online JSON to C# convertor such as jsonformatter.org or
3 – Use Visual Studios Paste Special -> Paste JSON as Classes option.

Paste JSON as Classes in Visual Studio

This is a little known feature of Visual Studio and is simple to use. For example if I copied the following JSON (taken from json.org/example.html) into my clipboard ..

JSON example

and selected Paste Special -> Paste JSON As Classes from the Edit menu ..

Paste JSON As Classes

Visual Studio would create the following classes ..

Visual Studio generated classes

which you can easily create an instance of by deserializing the same JSON string.

Convert JSON to object

This is a lot easier than manually creating the DTO and while many of the convertors online are great having something like this built in is better. And as you may have noticed above there’s also a Paste XML As Classes option too if you need it.

Leave a Reply

Your email address will not be published. Required fields are marked *