0

I am new to api stuff. I want to get the result of this api(http://services.groupkt.com/country/get/all) in c# code. can you help me by suggesting any code and tutorial as well. thanks i have tried this code but it doesnot work.

public async Task DownloadData()
{
    string url = string.Format("http://services.groupkt.com/country/get/all");

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Accept", "application/json");

    var jsonString = await client.GetStringAsync(url);

    JToken token = JToken.Parse(jsonString);

    foreach (var item in token)
    {
        txtarea.Value= item.ToString();
    }
}
5
  • 1
    "it doesnot work" has several meanings. Are you getting any compiler error, runtime error, or you are not getting the expected results? Commented Feb 1, 2017 at 6:09
  • i am trying to display result in a textarea but it doesnot show any result. Commented Feb 1, 2017 at 6:11
  • Use a browser to visit that url and see what you are getting? or you can also use fiddler to test the service url. Commented Feb 1, 2017 at 6:17
  • i am getting json format. i am able to get result using jquery but i have to do it in c# Commented Feb 1, 2017 at 6:19
  • Use Json2CSharp.com (or the equivalent feature in Visual Studio to paste JSON as a class). Then using JsonConvert to deserialize into that object, now you have a class you can deal with. Commented Feb 1, 2017 at 6:48

3 Answers 3

3

First of all use

client.GetStringAsync(url).Result

instead of

client.GetStringAsync(url)

Second after you received the json, it becomes very simple to parse the result. I saw the previous answeres and they were all using a loop, which is not a good idea in my opinion to parse. Use Newtonsoft.Json library and its very handy in such situations. I've parsed your json response using this library. Make a class of result, i.e.

    public class result
    {
        public string name { get; set; }
        public string alpha3_code { get; set; }
        public string alpha2_code { get; set; }
    }

put this code after getting json response for parsing your json.

JObject jsonResponse = JObject.Parse(jsonString);
JObject objResponse = (JObject)jsonResponse["RestResponse"];
Dictionary<string, JArray> _Data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, JArray>>(objResponse.ToString());
var results = _Data["result"].ToObject<List<result>>();

It works perfectly, I've tested this.

Don't forget to add Newtonsoft.Json AND Newtonsoft.Json.Linq namespaces

Sign up to request clarification or add additional context in comments.

1 Comment

been looking for this solution for 2 days.. every other solution was too complex and does not work... thanks mate
0

Your code fetches the response correctly. But parsing incorrectly.

Try the below full parsing code.

public async Task DownloadData()
{
    string url = string.Format("http://services.groupkt.com/country/get/all");
    string top_parent_key_name = "RestResponse";
    string second_parent_key_name = "result";
    string field_one_key_name = "name";

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Accept", "application/json");

    var jsonString = await client.GetStringAsync(url);

    JToken token = JToken.Parse(jsonString);

    foreach (var item in token[top_parent_key_name][second_parent_key_name])
    {
        txtarea.InnerText = item[field_one_key_name].ToString();
    }
}

4 Comments

Just replace your front end control names with this. For example txtarea.Value = item[field_one_key_name].ToString();
i am calling await DownloadData(); in button click function and displaying result in label but its not showing anything
Try this txtarea.InnerText = item[field_one_key_name].ToString();
Maybe this could help, it suggests casting to JObject then using Properties() to get the values: accessing all items in the JTOKEN, json.net
0

Just to add, I would prefer dynamics here so the code communicates more clearly.

public async Task DownloadData()
{
    string url = $"http://services.groupkt.com/country/get/all";

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Add("Accept", "application/json");

    string response = await client.GetStringAsync(url);

    dynamic json = JToken.Parse(response);

    foreach (var item in token.RestResponse.result)
    {
        //Note: Your over writing the text here for each item you pass
        //      Did you mean to concat instead? += "\n\r" + item.name;
        txtarea.InnerText = item.ToString();
    }
}

Now as for just doing txtarea.InnerText = ... in a question you labeled with "ASP.NET-Web-Api" seems a bit odd, is it an ASP.NET MVC with Web Api or a more classic Web Forms application?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.