Categories
Programación

How to use Quicktype.io JSON to C#

Using quicktype you can handle all your object in C# from a JSON file, is just really simple to do. In this quick tutorial you would learn how to do it.

This is a simple “How to” use Quicktype and not die while doing so. It’s seems to me that there is not to much documentation around about this. But I did like the web APP and that’s why I want to take some time to explain how to use it for newbies.

I would do a little demonstration.

First I would create a new Xamarin Forms project in Visual Studio, the demo is a Pokedex just like the one they preview on their web page.

Quicktype Web Page picture

So the name of the project in Visual Studio will be Pokedex and the class I would be using will be PokedexData. This part is quite simple.

Now the project would be really simple, I use NVVM so you should have that in mind while reading my code.

Pokedex NVVM Structure
MainPage Example

So that’s the main page it’s just a button to load a Pokemon, with it’s picture, name and type of pokemon.

In this case we go to Quickytpe and paste the information from the web page that has the JSON code this allows us to get all the objects. Json File

JSON Code from WebPage

We don’t need Postman because I already have a JSON structure so just paste it in Quicktype.

I won’t publish the model code because Quicktype would do everything for us, you could look for it in my GITHUB if you have any doubt. I did comment some part of the code related to egg property. But the most interesting part of the code is this:

Because Quicktype is doing the hardwork for us. We just need to create a service for the API that would help us to get the information to transfer the data to the Objects in C# and pass them to our MainViewModel.

As you can see my Service is quite simple, the first part of the code is a Connectivity Status to see if there is Internet on the device.

The Rest Service is the one doing all the magic. It goes to the url of the Json over HTTP and thanks to Quicktype I just need to use:

pokedexData = PokedexData.FromJson(content); in that way we fill all the objects from the Model called PokedexData. The MainViewModel will show the information from the PokedexData when the button to load is clicked.

In the command region the button now get’s the information from the service and fills the MainPage, labels and image.

Note: I did not use the uri for the image since the information on the JSON is going to an Http and the image are now on Https and I didn’t want to do more work on it since is a demo for Quictype.

The code is available in my Github.

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *