elektra
elektra

Reputation: 115

How to save JSON response into an array

I have three URLs that I loop through and try to fetch result from. The URLs are basic, like:

http://foo.bar/id/2563
http://foo.bar/id/1453
http://foo.bar/id/7321

My foreach looks something like this:

foreach (var url in urls){
  HttpResponseMessage response = client.GetAsync(url).Result;
  response.EnsureSuccessStatusCode();

  body = await response.Content.ReadAsStringAsync();
  result = JsonConvert.DeserializeObject<JsonData>(body);
}

Here is the thing, each JSON has

[{
  id: 1,
  name: John,
    Address: {
      zipcode: '',
      town: ''
    }
}]

The idea for me is to display all Address.zipcode and Address.town of each JSON.

For some reason though my web page displays only the data from the first url, and not from the second and third urls

This is my model:

public class JsonData {
 public int id { get; set; }
 public string name { get; set; }
 public Dictionary<string, string> Address{ get; set; }
}

This is just a code I wrote, because the code is fine but I don't know why I am only seeing one zipcode and one town out of many.

It seems like in the foreach loop, only one data is saved result whereas I am trying to save all of them.

My HTML is basic and looks like this:

@foreach(var item in result) {
  <p> @item.Address.zipcode - <small>@item.Address.town</small> <p>
}

Upvotes: 0

Views: 846

Answers (1)

Don't actually get what you are asking for because lack of information. But you can push deserialized "results" into an array.

//Create an empty array of type JsonData
JsonData[] results = Array.Empty<JsonData>();

foreach (var url in urls)
{
    HttpResponseMessage response = client.GetAsync(url).Result;
    response.EnsureSuccessStatusCode();

    var body = await response.Content.ReadAsStringAsync();
    
    //Push each deserialized response into the results array
    Array.Resize(ref results, results.Length + 1);
    results[results.GetUpperBound(0)] = JsonSerializer.Deserialize<JsonData>(body);
}

Then you can iterate over the results array.

Upvotes: 3

Related Questions