public static void UpdateBookFromJson(string json, Book book)
{
// There are many volumeInfos, and many are incomplete. So, to find a field like
// "title", we use LINQ to scan multiple volumeInfos.
JObject results = JObject.Parse(json);
if (results.Property("items") == null)
return;
var infos = results["items"].Select(token => (JObject)token)
.Where(obj => obj.Property("volumeInfo") != null)
.Select(obj => obj["volumeInfo"]);
Func<string, IEnumerable<JToken>> GetInfo = (propertyName) =>
{
return infos.Select(token => (JObject)token)
.Where(info => info.Property(propertyName) != null)
.Select(info => info[propertyName]);
};
foreach (var title in GetInfo("title").Take(1))
book.Title = title.ToString();
// Find the oldest publishedDate.
var publishedDates = GetInfo("publishedDate")
.Select(value => ParseDate(value.ToString()))
.Where(date => date != null)
.OrderBy(date => date);
foreach (var date in publishedDates.Take(1))
book.PublishedDate = date;
foreach (var authors in GetInfo("authors").Take(1))
book.Author = string.Join(", ", authors.Select(author => author.ToString()));
foreach (var description in GetInfo("description").Take(1))
book.Description = description.ToString();
foreach (JObject imageLinks in GetInfo("imageLinks"))
{
if (imageLinks.Property("thumbnail") != null)
{
book.ImageUrl = imageLinks["thumbnail"].ToString();
break;
}
}
}
}