1 of 13

JSON

CS 240 – Advanced Programming Concepts

2 of 13

Structure of JSON Documents

  • Supported data types: Objects, Arrays, Numbers, Strings, Boolean, Null
  • Objects delimited by { … } with comma-separated properties in between
    • { “name”: “Bob”, “age”: 32, “alive”: true }
  • Arrays delimited by [ … ] with comma-separated elements in between
    • [ “testing”, 1, 2, 3, { “gpa”: 3.4 } ]
  • Examples
    • Verbose
    • Simple

2

3 of 13

Parsing JSON Data

  • Most languages provide JSON parsers, so there’s no need to write your own
  • Three Major Types of Parsers
    • Stream Parsers
      • Tokenizers that return one token at a time from the JSON data file
    • DOM Parsers
      • Convert JSON text to an in-memory tree data structure (the tree is called a DOM, or “document object model”)
      • After running the parser to create a DOM, traverse the DOM to extract the data you want
    • Serializers / Deserializers
      • Use a library to convert from JSON to Java Objects (and vice versa)
      • Gson and Jackson are both popular libraries

3

4 of 13

JSON Parsing Examples

  • Source File: cd_catalog.json
  • Domain Object: CD
  • DOM Parser Example
    • JsonDomParserExample.java
  • Stream Parser Example
    • JsonStreamParserExample.java

4

5 of 13

JSON Parsing Examples (cont.)

  • Deserialization using the Gson library from Google
  • Simple Deserialization Example
  • Complex Deserialization Example

5

6 of 13

Generating JSON Data

  • Programs often need to generate (or create) JSON data
  • You can type JSON data yourself (it’s just text), but it’s better to use a library that handles tricky special cases like escaping special characters)
  • Three Ways to Generate JSON
    • Create DOM tree in memory, and then tell the tree to write itself to text
    • Write the data as a stream, one token at a time
    • Use a “serializer” class that converts Java objects to Json

6

7 of 13

JSON Generation Examples

  • Domain Objects: CDFactory (used to generate Java objects to be converted), Catalog, CD
  • DOM Generator Example
    • JsonDomGenerationExample.java
  • Stream Generator Example
    • JsonStreamGenerationExample.java

7

8 of 13

JSON Generation Examples (cont.)

  • Serialization using Gson
  • Simple Serialization Example
  • Complex Deserialization Example

8

9 of 13

Making Gson Available to Your Project

Three Ways:

  1. Add the dependency from File / Project Structure
    • Search for gson and select the latest version
  2. Create a Maven project and add the dependency to your pom.xml file

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

<version>2.10.1</version>

</dependency>

  • Create a Gradle project and add the dependency to your build.gradle file

implementation group: 'com.google.code.gson', name: 'gson', version: '2.10.1'

10 of 13

Gson Type Adapters

  • Sometimes Gson needs help to know how to serialize (write) and/or deserialize (read) an object
  • Examples:
    • You want to write an attribute in something other than its default format
    • You want to deserialize a json string to an object whose class does not have a no-argument constructor
    • You want to deserialize a json string into one of several subclasses
    • You want to deserialize a json string into one of several implementing classes of an interface
    • You want to deserialize a Json string to an object whose instance variables are interfaces or abstract classes
    • You have complex parsing or serialization logic

10

11 of 13

Type Adapter Example: Standard �Type Adapter

  • In this example, we have an Automobile interface with Car and Truck implementations.
  • By including a type variable, we can use a TypeAdapter to determine what it’s type was when we serialized it and create the appropriate subclass.
  • Example code
  • Fast but not trivial to write

11

12 of 13

Type Adapter Example: Deserializer

  • Performs the same function as a standard type adapter but easier to write
  • Simpler because it parses the entire json string into a DOM tree for easy access
  • Slower for the same reason
  • Can use a JsonDeserializationContext parameter to cause Gson to do parts of the parsing
  • Example Code
  • Slower but easier to write

12

13 of 13

Type Adapter Example: RuntimeTypeAdapter

  • By using an extra class written by the Gson team, but not included in the Gson library, we can simplify the example and serialize and deserialize classes that implement an interface without specifying a type variable and without writing a TypeAdapter.
  • Get the RuntimeTypeAdapterFactory class in one of two ways:
    • Copy from this github repo (put the code in the package specified in the source file)
    • Install the gson-extras library from maven
  • Example code
  • Fast and easy to write but requires a separate class that isn’t a standard part of Gson
    • No need to include a type variable in the abstract parent class