Like Json.NET, gson provides a way to specify the destination class to which you're deserializing a JSON object. In fact, it's the same method you used in the recipe Reading and writing JSON in Java, in Chapter 1, Reading and Writing JSON on the Client.
You'll need to include the gson JAR file in your application, just as you would for any other external API.
You use the same method as you use for type-unsafe JSON parsing using gson using fromJson
, except you pass the class object to gson as the second argument, like this:
// Assuming we have a class Record that looks like this: /* class Record { private String call; private float lat; private float lng; // public API would access these fields } */ Gson gson = new com.google.gson.Gson(); String json = "{ \"call\": \"kf6gpe-9\", \"lat\": 21.9749, \"lng\": 159.3686 }"; Record result = gson.fromJson(json, Record.class);