call API and read json file

عبدالله القرني 21 Reputation points
2021-05-23T21:23:30.087+00:00

Hello,
I have a problem getting data from the JSON file that I got by calling API.
I was able to call API and get the JSON file as text but when I wanted to split the JSON file into C # variables, I couldn't.
This is the json file: https://paste.myst.rs/loj5h85d
and this is my c# script: `using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace ApiCalling
{

public class area
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string CountryCode { get; set; }
    public string EnsignUrl { get; set; }
}
public class currentSeason
{
    public int Id { get; set; }
    public string StartDate { get; set; }
    public string EndDate { get; set; }
    public int CurrentMatchday { get; set; }
    public string Winner { get; set; }
}
public class competition
{
    public int Id { get; set; }
    public area Area { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public string EnsignUrl { get; set; }
    public string Plan { get; set; }
    public currentSeason CurrentSeason { get; set; }
    public int NumberOfAvailableSeasons { get; set; }
    public string LastUpdated { get; set; }
}

public class theComptitions
{
    public List<competition> Competitions { get; set; } = new List<competition>();
    public int Count { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var Apiclient = new HttpClient())
        {
            // New code:
            Apiclient.BaseAddress = new Uri("http://api.football-data.org/");
            Apiclient.DefaultRequestHeaders.Accept.Clear();
            Apiclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            Apiclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("X-Auth-token", "MyApiCode");

            // GET
            HttpResponseMessage response = await Apiclient.GetAsync("v2/competitions");
            if (response.IsSuccessStatusCode)
            {
                theComptitions combtitions = await response.Content.ReadAsAsync<theComptitions> ();
                Console.WriteLine(combtitions.Count);

            }
        }
    }
}

}
`
And I have another question: How can I get one of the combinations?

Developer technologies C#
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-05-24T22:33:29.237+00:00

    I just de-serialized your data using Newtonsoft.Json by copying the json you provided, create a new class file, deleted the class and used Visual Studio edit, Paste Special, Paste JSON as class then saved the file. For the json I placed the code into a file, read it back using File.ReadAllText which returns a string (equivalent to your data returned)

    99230-figure1.png

    using System;  
    using System.IO;  
    using Newtonsoft.Json;  
      
    namespace Demo  
    {  
        public class JsonHelpers  
        {  
            public static TModel ReadJsonFromFile<TModel>(string fileName)  
            {  
                var model = default(TModel);  
      
                if (!File.Exists(fileName)) return model;  
                  
                var json = File.ReadAllText(fileName);  
                model = JsonConvert.DeserializeObject<TModel>(json);  
      
                return model;  
      
            }  
        }  
    }  
      
    

    Then called as follows

    var data = JsonHelpers.ReadJsonFromFile<Rootobject>("data1.json");  
    

    If using System.Text.Json the same will work

    using System;  
    using System.Collections.Generic;  
    using System.IO;  
    using System.Text.Json;  
      
    namespace JsonLibrary  
    {  
    	public class JSonHelper  
    	{  
    		public static T DeserializeObject<T>(string json)  
    		{  
    			return JsonSerializer.Deserialize<T>(json);  
    		}  
    	}  
    }  
      
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.