Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying The JavaScript JSON Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
The JavaScript JSON Cookbook

The JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie
1 (2)
close
close
The JavaScript JSON Cookbook

The JavaScript JSON Cookbook

1 (2)
By: Ray Rischpater, Brian Ritchie

Overview of this book

If you're writing applications that move structured data from one place to another, this book is for you. This is especially true if you've been using XML to do the job because it's entirely possible that you could do much of the same work with less code and less data overhead in JSON. While the book's chapters make some distinction between the client and server sides of an application, it doesn't matter if you're a frontend, backend, or full-stack developer. The principles behind using JSON apply to both the client and the server, and in fact, developers who understand both sides of the equation generally craft the best applications.
Table of Contents (12 chapters)
close
close
11
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/.

Create a Note

Modal Close icon
You need to login to use this feature.
notes
bookmark search playlist font-size

Change the font size

margin-width

Change margin width

day-mode

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Delete Bookmark

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Delete Note

Modal Close icon
Are you sure you want to delete it?
Cancel
Yes, Delete

Edit Note

Modal Close icon
Write a note (max 255 characters)
Cancel
Update Note

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY