Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The JavaScript JSON Cookbook

You're reading from   The JavaScript JSON Cookbook Over 80 recipes to make the most of JSON in your desktop, server, web, and mobile applications

Arrow left icon
Product type Paperback
Published in Jun 2015
Publisher
ISBN-13 9781785286902
Length 192 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (12) Chapters Close

Preface 1. Reading and Writing JSON on the Client FREE CHAPTER 2. Reading and Writing JSON on the Server 3. Using JSON in Simple AJAX Applications 4. Using JSON in AJAX Applications with jQuery and AngularJS 5. Using JSON with MongoDB 6. Using JSON with CouchDB 7. Using JSON in a Type-safe Manner 8. Using JSON for Binary Data Transfer 9. Querying JSON with JSONPath and LINQ 10. JSON on Mobile Platforms 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/.

You have been reading a chapter from
The JavaScript JSON Cookbook
Published in: Jun 2015
Publisher:
ISBN-13: 9781785286902
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime