I’m querying the Google Books API, and I’m parsing the books into a custom object like this:
foreach (JToken item in items)
{
try
{
FoundBookViewModel viewModel = new FoundBookViewModel
{
Title = item.SelectToken("volumeInfo.title").ToString(),
Isbn13 = item.SelectToken("volumeInfo.industryIdentifiers[1].identifier").ToString(),
Authors = item.SelectToken("volumeInfo.authors").Select(x => x.ToString()).ToList().Aggregate((i, j) => i + ", " + j),
Pages = item.SelectToken("volumeInfo.pageCount").ToString(),
ImageUri = item.SelectToken("volumeInfo.imageLinks.smallThumbnail").ToString()
};
newList.Add(viewModel);
}
catch (Exception)
{
newList.Add(new FoundBookViewModel());
}
}
However, sometimes not all data is available. Sometimes there is no ‘pageCount’, sometimes there is no ‘ISBN13’, etc. In those cases an exception is thrown at the ToString() part.
So what I want is this: when an exception is thrown for one of the properties, I just want it to be an empty string. But I don’t know a clean way to accomplish this.
I tried multiple things:
- I wrapped the whole thing inside a try catch, but then I don’t know what property was empty, so I can’t ‘fill’ it with an empty string.
- I tried using safe casting (‘as string’) but that operation is not available on SelectToken().
- Couple of other things that didn’t work anyway.
Of course I could put every operation inside its own try catch, but that will result in 5 try catch blocks in this situation, so that’s not what I’m looking for.
Who knows a clean way to solve this? Btw. I choose to use LINQ to JSON instead of materializing it directly because the Google Books API doesn’t neatly map to simple entities (the JSON contains lots of nesting).
If you don’t want to throw exception – don’t…
I.e. you can change
item.SelectToken("volumeInfo.pageCount").ToString()into: