JSON stands for JavaScript Object Notation and is a definition for a very lightweight format for transmitting data through object serialization. This means that the message we received from the Google Places API is actually a set of objects. All we need to do is properly parse these objects, and it will be a simple matter to understand the search results. Unity does actually have a built-in JSON library; but, at the time of writing this book, it could not parse the Google Places API response. Fortunately, there are plenty of resources available to parse JSON.
Since the Unity engine could not effectively parse the response, it was decided to use a library called TinyJson. TinyJson is another open source library pulled from GitHub, but parts had to be rewritten in order to support the iOS platform. However, a couple calls to the System.Linq
namespace were left in. If you plan to run this code on an iOS device, make sure that your scripting backend is set to IL2CPP
.
Now that we have the big picture, we will look at the sample snippet of code that shows how we will make a search request to the API:
//this code is run as part of a coroutine var req = new WWW("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670,151.1957&type=food&radius=500&key={yourkeyhere}"); //yield until the service responds yield return req; //extract the JSON from the response var json = req.text; //use the TinyJson library JSONParser to de-serialize the result into //an object called SearchResult var searchResult = TinyJson.JSONParser.FromJson<SearchResult>(json);
This code is very similar to the code we used to download the images from the Google Static Maps API, except now we are using the WWW
method to return the JSON text string and parsing it into an object called SearchResult
. SearchResult
is defined by reading the JSON and extracting the properties and object hierarchy into class definitions. Unfortunately, this has to be a manual process because we can't use any dynamic code generation if we want to support iOS. Fortunately, though, there are plenty of tools available that allow us to convert JSON into the required class definitions.
In order for you to see the complete process and the magic of JSON, we will use an online tool to construct our SearchResult
class hierarchy. Perform the following instructions to perform the exercise:
{
) to the ending curly brace (}
) at the bottom.
Generated class hierarchy from JSON response message
RootObject
class to be our SearchResult
class. RootObject
is just a name assigned to root or top-level unnamed object in the response.The sample code we have shown above and the generated class hierarchy was used to build the GooglePlacesAPIService
. The service itself has several other features, but now you at least understand the core of how the service was built and how to build other such services that consume JSON. In the next section, we will set up the new service.
18.118.164.151