In next posts we will create little app what will use public web api data and show it on screen. First task is to create classes what correspond to json data web api is returning.
There are several ways to create C# classes from JSON API response in Visual Studio. One of them is to use a tool called JSON to C#¹ which you can install from the Visual Studio Marketplace. This tool allows you to paste your JSON data and generate C# classes automatically. You can access it from the Tools menu or by right-clicking on your project folder¹.
Another way is to use Web Essentials³, a Visual Studio plugin that has a feature called Paste Special. This feature lets you copy your JSON data and paste it as a C# class in your code editor³. You can find it under the Edit menu.
There are also some web tools that can help you generate C# classes from JSON data, such as app.quicktype.io³ or json2csharp.com³. These tools allow you to enter your JSON data and download or copy the generated C# code.
My personal favoutite is Paste Special, but all of options are good. In this exaple I use YTS api https://yts.mx/api to fetch latest movie releases. Latest releases list can be found at https://yts.mx/api/v2/list_movies.json . If you open it web browser then most probali it is showed to you in beautified format. To avoid any errors on json structure, open page source view.
Select all the content of response (Click on response text and select all using Ctrl+A or mouse)
In Visual Studio make new class file for json class structure and go to menu Edit -> Paste Special -> Paste JSON as Classes.
If this opton is disabled then data in clipboard is not recognized ad json.
Now all classes are created for you.
Root element does not have name in json response, so it is named as Rootobject. Rename it to something more meaningful:
Also if you plan to manipulate data then change array T types to List<T>.ApiResponse Class (6 downloads)
Continue to Consuming json API in C# application – part 2
(1) JSON to C# – Visual Studio Marketplace. https://marketplace.visualstudio.com/items?itemName=DangKhuong.JSONtoC
(3) How to auto-generate a C# class file from a JSON string. https://stackoverflow.com/questions/21611674/how-to-auto-generate-a-c-sharp-class-file-from-a-json-string.
(4) Quickly Generate C# Classes from JSON Responses. https://learn.microsoft.com/en-us/shows/windows-store-developer-solutions/quckly-generate-c-classes-from-json-responses.
(5) .net – Generate C# classes from JSON Schema – Stack Overflow. https://stackoverflow.com/questions/6358745/generate-c-sharp-classes-from-json-schema.
Pingback: Consuming json API in C# application - part 2 - Software Blog