Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

How to deserialize an object using gson for Java


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.

Getting ready

You'll need to include the gson JAR file in your application, just as you would for any other external API.

How to do it…

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);

How it works…

The fromGson method always...