Click here to Skip to main content
15,892,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 0:01am

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:

C#
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.

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


Now you can iterate on the array.

C#
foreach(var location in data)
{
  // your logic here
}
 
Share this answer
 
v3
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[^]
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900