I’ve been looking for a long time for how to put an api result in Json format on a CardView.
But unfortunately there is no step by step guide to do something like this…
I’ve finally made it and I want to share it with the community.
The result looks like this:
Note: In this example can not see the icon to share because it can’ t be seen in the companion
In this example we are going to use the newsapi.org API.
First of all we create our link on the api website. We make sure that the result obtained is a valid Json file.
If we paste the link into the web browser and hit the enter we will get the result of the api:
What we’re seeing is a mess. But it doesn’t matter. To get an idea of the data it shows us, we can paste the same in the web JSON Formatter & Validator and we’ll see it sorted in a slightly more visual way.
The most important thing to keep in mind is the word the Json starts with. In this case we see that everything is contained inside “articles”.
Then we see that each data has its objects and values. We have author, title, description, urlToImage, url…
Here we must have in clear which are the data that we want to obtain.
In the example, we are going to obtain the values of content, and urlToImage
Now in Kodular we will use these components:
NOTE: Here in this example I have used the Cardview extension by Andres Cotes.
We create our project (or we use an existing one, it doesn’t matter) and we create a variable for articles, another one for each one of the data we want to obtain, in this case urlToImage and content. We initialize them as empty lists.
We also created a text variable (decodeJson) to decode the Json with the web component. This converts the son into lists.
Here we assign the url of the api to the web component and access it with Web1.Get.
Then we’ll use these blocks:
First we decode the Json. Then what we do is separate “articles” from the rest of the data.
Then into the FOR EACH we fill the lists with the values we want to obtain. In this case “content” and “urlToImage”.
Finally we complete the cardview with the obtained lists and we indicate that it shows it in a vertical scroll arrangement.
If we want to get more values, we just have to create more variables and add items to the lists inside the for each