'Getting specific data from JSON Model
Here is my JSON model for trying to get info from Google Maps API. I am trying to get the "name" and "vicinity" from the "Result "class, but am having trouble with getting the data values from the IList, preferably i would like all the name and vicinity attributes to be returned as a string. Anyone got any ideas? Not familiar with using IList's on projects.
public record Location
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Northeast
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Southwest
{
public double lat { get; set; }
public double lng { get; set; }
}
public record Viewport
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public record Geometry
{
public Location location { get; set; }
public Viewport viewport { get; set; }
}
public record OpeningHours
{
public bool? open_now { get; set; }
}
public record Photo
{
public int height { get; set; }
public IList<string> html_attributions { get; set; }
public string photo_reference { get; set; }
public int width { get; set; }
}
public record PlusCode
{
public string compound_code { get; set; }
public string global_code { get; set; }
}
public record Result
{
public string business_status { get; set; }
public Geometry geometry { get; set; }
public string icon { get; set; }
public string icon_background_color { get; set; }
public string icon_mask_base_uri { get; set; }
public string name { get; set; }
public OpeningHours opening_hours { get; set; }
public IList<Photo> photos { get; set; }
public string place_id { get; set; }
public PlusCode plus_code { get; set; }
public double rating { get; set; }
public string reference { get; set; }
public string scope { get; set; }
public IList<string> types { get; set; }
public int user_ratings_total { get; set; }
public string vicinity { get; set; }
}
public record ResourceData
{
public IList<object> html_attributions { get; set; }
public IList<Result> results { get; set; }
public string status { get; set; }
}
public record record_GooglePlacesAPI
{
public DateTime TimeCreated { get; set; } = DateTime.UtcNow;
public ResourceData resourceData { get; set; }
}
Solution 1:[1]
Try running a simple LINQ query on the data returned from google API like the following
//string holding google api response
string googleResponse = string.Empty;
var googleapi = JsonConvert.DeserializeObject<record_GooglePlacesAPI>(googleResponse);
//Linq query that returns list of names and vicinities
List<string> vicinities = googleapi.resourceData.results.Select(r => r.vicinity).ToList();
List<string> names = googleapi.resourceData.results.Select(r => r.name).ToList();
it should return you a list of strings holding names and viciniteis
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mahmoud Ibrahim |
