Press ESC to close

Get JSON Data with Xamarin

Hello friends. I had written before about how to withdraw data from JSON, but there was a lot of mail and comment on this topic. That’s why I wanted to write a more detailed article, especially Xamarin. Actually, it has nothing to do with Xamarin. You can do the same for all .NET platforms.

We need to have a service because we will pull JSON data. I wanted to use existing sample services instead of writing a service specific to this topic. In my previous articles, I mentioned how to write service. Search. I found a service that gives a list of Nobel Prize winners. We will make transactions through this service. You can reach here.

First of all, in our project, we must have a class to send and receive data from a service. Here we create a HttpClient and do our transactions through this client. You can change this class according to the operations you want to do. You can add a token if you want. I’ve added it below to be an example. It pulls our data from this service class with GetAsync method. Of course, this function requires a return type and url as parameters.

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace XamJson.Helpers
{
    class Service
    {
        public async Task<TResult> GetAsync<TResult>(string uri)
        {
            try
            {
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Add("accept-language", "en");
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "token");

                HttpResponseMessage response = await httpClient.GetAsync(uri);
                string serialized = await response.Content.ReadAsStringAsync();
                TResult result = JsonConvert.DeserializeObject<TResult>(serialized);
                return result;
            }
            catch (Exception e)
            {
                App.Current.MainPage.DisplayAlert("Error", "General Error", "OK");
                return default(TResult);
            }
        }
    }
}

We have to build our models. There is a very useful site to create the model you can use here. When you copy all your data here and press the generate button, the models are returned to you.

Let’s add this model to our project. When we generate the data, the model is as follows.

using System.Collections.Generic;

namespace XamJson.Models
{
    public class Laureate
    {
        public string id { get; set; }
        public string firstname { get; set; }
        public string surname { get; set; }
        public string motivation { get; set; }
        public string share { get; set; }
    }

    public class Prize
    {
        public string year { get; set; }
        public string category { get; set; }
        public string overallMotivation { get; set; }
        public List<Laureate> laureates { get; set; }
    }

    public class Nobel
    {
        public List<Prize> prizes { get; set; }
    }
}

Then we need to do the necessary operations on the page we want to call the data. What we need to do here is to get an instance from the service class and run GetAsync from this service. You can see that the model works as a return type. The rest depends on how you use it. If you wish, you can show certain prizes on the screen or if you throw a ListView and bind all the data here, you can show all the data on the screen.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using XamJson.Helpers;
using XamJson.Models;

namespace XamJson
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        Service service;
        public MainPage()
        {
            InitializeComponent();
            service = new Service();
            GetNobelPrizes();
        }

        private async void GetNobelPrizes()
        {
            var takenData = await service.GetAsync<Nobel>("http://api.nobelprize.org/v1/prize.json");
        }
    }
}

In fact, these operations are so simple and easy. You can pull all kinds of data as you wish. If you have questions, you can reach us by e-mail or comment. Good work.

Comments (2)

    • omersezersays:

      Sunday September 15th, 2019 at 08:15 PM

      Selam Ali,

      Nereye ne Bind etmek istiyorsun eğer ki sayfaya bind etmek istiyorsan; C# tarafında this.bindingContext ile bin edebilirsin. Listview için is yine aynı şekilde ama xaml kısmında itemsource kısmına Binding . yapman gerekir. Ardından field alanı ile ekranda gösterebilirsin.

Leave a Reply

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