GoogleCloudSamples.Services.BookDetailLookup.UpdateBookFromJson C# (CSharp) Method

UpdateBookFromJson() public static method

Updates book with information parsed from a json response from Google's Books API.
public static UpdateBookFromJson ( string json, Book book ) : void
json string A response from Google's Books API.
book GoogleCloudSamples.Models.Book Fields in book will be overwritten.
return void
        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;
                }
            }
        }
    }