Click here to Skip to main content
13,804,222 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
am using NewtonSoft to parse a JSON Api call.

The code must remain in the same format it is in.

My only problem is that I cannot iterate through the values of the JSON in a foreach loop.

How can I solve this problem?

public async Task callWebApi()
    {
        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(new HttpMethod("GET"), "https://www.metaweather.com/api/location/search/?lattlong=50.068,-5.316"))
            {
                var response = await httpClient.SendAsync(request);

                using (HttpContent content = response.Content)
                {


                    var jsonString = await response.Content.ReadAsStringAsync();
                    var data = JsonConvert.DeserializeObject<Object>(jsonString);
                Console.WriteLine("I need to parse distance, title, location_type, woeid,latt_long so that I can iterate through it using a foreach loop");
                Console.WriteLine(data);
                Console.Read();
                    // I don't know how to get the values of the json




                }
            }
        }


Here is a link to the working code:



What I have tried:

The problem is that I cannot iterate using a foreach loop.
Posted
Updated 8-Dec-18 1:01am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

you need to create a class that represents your json object in C# and then deserialized to that. You can use visual studio too for getting the json or you can use json2csharp.com for that.


The class for your json is:

public class Location
{
    public int distance { get; set; }
    public string title { get; set; }
    public string location_type { get; set; }
    public int woeid { get; set; }
    public string latt_long { get; set; }
}


As you are receiving multiple objects i.e. an array you need to deserialize to an array of the above type.

var data = JsonConvert.DeserializeObject<Location[]>(jsonString);


Now you can iterate on the array.

foreach(var location in data)
{
  // your logic here
}
  Permalink  
v3
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

This is one of many common qestions asked on JSON Deserialization, so I have written an article to answer these questions: Working with JSON in C# & VB[^]
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.181218.1 | Last Updated 8 Dec 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100