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

Reading and writing JSON in Java


Java, like C++, predates JSON. Oracle is presently working on adding JSON support to Java, but in the meantime, several implementations providing JSON support are available on the Web. Similar to the C++ implementation you saw previously in this chapter, you can convert between JSON and Java using a third-party library; in this case, packaged as a Java archive (JAR) file, whose implementation typically represents JSON objects as a tree of named objects.

Perhaps the best Java implementation of JSON parsing is Gson, available from Google at http://code.google.com/p/google-gson/ licensed under the Apache License 2.0.

Getting ready

First, you'll need to get Gson; you can do this by doing a read-only checkout of the repository using SVN over HTTP with SVN by using the following command:

svn checkout http://google-gson.googlecode.com/svn/trunk/google-gson-read-only

Of course, this assumes that you have a Java development kit (http://www.oracle.com/technetwork/java/javase/downloads/index.html) and SVN (TortoiseSVN is a good client for Windows available at http://tortoisesvn.net/downloads.html) installed. Many Java IDEs include support for SVN.

Once you check out the code, follow the instructions that come with it to build the Gson JAR file, and add the JAR file to your project.

How to do it...

To begin, you need to create a com.google.gson.Gson object. This class defines the interface you'll use to convert between JSON and Java:

Gson gson = new com.google.gson.Gson(); 
String json = "{\"call\": \"KF6GPE\", \"type\": \"l\", \"time\":
\"1399371514\", \"lasttime\": \"1418597513\", \"lat\": 37.17667,
\"lng\": -122.14650,\"result\":\"ok\"}";
com.google.gson.JsonObject result = gson.fromJson(json, 
JsonElement.class).getAsJsonObject(); 

The JsonObject class defines the top-level object for containing a JSON object; you use its get and add methods to get and set attributes, like this:

JsonElement result = result.get("result").getAsString();

The Gson library uses the JsonElement class to encapsulate a single JSON value; it has the following methods that let you get the value contained in JsonElement as a plain Java type:

  • getAsBoolean, which returns the value as Boolean

  • getAsByte, which returns the value as byte

  • getAsCharacter, which returns the value as char

  • getAsDouble, which returns the value as double

  • getAsFloat, which returns the value as float

  • getAsInt, which returns the value as int

  • getAsJsonArray, which returns the value as JsonArray

  • getAsJsonObject, which returns the value as JsonObject

  • getAsLong, which returns the value as long

  • getAsShort, which returns the value as short

  • getAsString, which returns the value as String

You can also learn about the type in JsonElement using one of the following methods:

  • isJsonArray, which returns true if the element is an array of objects

  • isJsonNull, which returns true if the element is null

  • isJsonObject, which returns true if the element is a composite object (another JSON tree) instead of a single type

  • isJsonPrimitive, which returns true if the element is a primitive type, such as a number or string

There's more…

You can also convert instances of your classes directly to JSON, writing something like this:

public class SimpleResult {
    public String result;
}

// Elsewhere in your code…
Gson gson = new com.google.gson.Gson(); 
SimpleResult result = new SimpleResult;
result.result = "ok";
String json = gson.toJson(result);	

This defines a class SimpleResult, which we use to create a single instance, and then use the Gson object instance to convert to a string containing the JSON using the Gson method toJson.

Finally, because JsonElement encapsulates a single value, you can also handle simple values expressed in JSON, like this:

Gson gson = new com.google.gson.Gson(); 
String piJson = "3.14";
double result = gson.fromJson(piJson, 
JsonElement.class).getAsDouble(); 

This converts the primitive value 3.14 in JSON to a Java double.

See also

Like the C# example, you can convert directly from JSON to a plain old Java object (POJO) in a type-safe manner. You'll see how to do this in Chapter 7, Using JSON in a Type-safe Manner.

There are other JSON conversion implementations for Java, too. For a complete list, see the list at http://json.org/.