{{announcement.body}}
{{announcement.title}}

Patterns of Reading JSON

DZone 's Guide to

Patterns of Reading JSON

JSON can be read or mapped to domain objects using two broad categories of APIs: Binding (High-Level) and Streaming (Low-Level).

· Java Zone ·
Free Resource

JavaScript Object Notion (JSON) is a de-facto standard for exchanging data over Web API. JSON is a recursive data structure and can be visualized as a key-value pairs tree.

There are two broad categories of APIs for reading information from JSON :

  • Streaming Based: It is parsing or visiting of JSON part by part. With each part iteration, you skip or map a part to Object/s. Part maybe {, [, field, value, : , } , and ] (JSON Tokens!).
Mapping parts in JSON
  • Binding based: Binding is mapping of JSON field to Programming Objects; these may be domain or abstractJSON is entirely parsed and mapped to objects.

This article goes through different patterns of Reading JSON data. Java is chosen for demonstrating these patterns.

JSON  —  Abstract Model Binding

JSON is mapped to the library provided objects or collections objects intermediately. Then, these objects are iterated for mapping with domain objects or for extracting information.

Formally, these intermediary objects are collectively called Parsed Tree³. The process of converting JSON to Parsed Tree is known as parsing².

These objects do not adequately express business knowledge; this is the reason for calling these objects: abstract.

In Action

Consider the extraction distance between New York and Washington from the output of a sample Google Distance Matrix API:

JSON


GSON is one of the libraries to parse JSON. The code for extracting distance is as:

Java
Repl.it → https://repl.it/@DM8tyProgrammer/NonDomainBinding

JSON  —  Domain Model Binding

Almost whole JSON is mapped directly to equivalent Domain or Business Objects; Domain object mimics the structure of JSON with identical fields and compatible types.

In Action

Consider Twitter’s Tweet object from Web API for a demonstration of this pattern.

JSON


The equivalent class would be for the above JSON:

Java

JSON
Java


You can verify: Classes mirror JSON field by field with the same name and compatible types. Some libraries offer relaxations in mappings: missing fields, unknown fields, field name mismatch, type mismatch, and conversion.

Jackson is a famous library for domain object mapping. Jackson provides an ObjectMapper API to read or write JSON. The code of mapping is as:

Java
Repl.it → https://repl.it/@DM8tyProgrammer/jackson

Expression Based Data Extraction

Selected data from JSON can be extracted using JSONPath, which is an algebraic expression for pointing fields. XPath inspired the idea of JSONPath.

Extraction using JSONPath can be described as:

  1. JSON Parsing: JSON is parsed into Abstract Objects or Parsed Tree.
  2. Expression Evaluation: An expression is passed to API exposed by the previous step to query JSON.

JSONPath Expression

In JSONPath context, JSON is considered as Tree. The below elements are concatenated to formulate expression:

  • The root of JSON is selected by $.
  • . selects the immediate child field.
  • .. selects any level child field.
  • ['<field name>'] or just name to select field.
  • [<number>] to access the nth array element.
  • [*] targets all fields of an array.

In Action

Again, consider the extraction distance between New York and Washington from the output of a sample Google Distance Matrix API:

JSON


The JSON path would be: $.rows[0].elements[0].distance.value. JSONPath can be evaluated with Jayway’s Jsonpath (notice name!) libraryThe code snippet for the extracting distance is as:

Java
Repl.it → https://repl.it/@DM8tyProgrammer/jsonpath

JSON Streaming Parsing

Aforementioned, streaming JSON means iterating JSON part by part. These parts are formally known as tokens. These may be a single character or group of characters.

In JSON Format Specification, the following tokens are defined:

  • Object Sentinels:: {:Start of Object, }: End of Object
  • Array Sentinels:: [: Start of Array, ]: End of Array
  • Literal Types:: Number, String, Boolean (true, false), null.

In Action

Consider a simple JSON to parse:

JSON


GSON and Jackson both feature a Streaming API. Jackson is arbitrarily chosen for demonstrating. The code for parsing JSON through streaming tokens is showcased below; with each iteration, data is pushed to the collections as:

Java
Repl.it → https://repl.it/@DM8tyProgrammer/stream-json

The code can be understood as iterating though tape having JSON tokens:

iterating through JSON example

Closing Notes

Binding API internally streams JSON for converting it into object form. It can be said Binding is a High-Level API.

Streaming, Abstract Model Binding, and Expression Based Extraction are used to select a part of data from JSON. Domain Model Binding method is used to extract the complete JSON information.

Expression-based JSON extraction is a declarative variant of Abstract Model Binding method; Instead of you writing code by hand for walking Parsed Tree, you are passing specifications to the API to extract data from JSON. It is a concise and flexible method; however, it is a slower variant.

Footnotes

  1. Reading JSON means Parsing² of JSON and mapping the data into Domain Objects.
  2. Parsing is a mechanism of converting formatted text into a data structure. In case of JSON parsing, the output data structure is of Tree type.
  3. Parsed Tree is the output data structure of JSON parsing.

References

  1. Introducing JSON, https://www.json.org/json-en.html.
  2. JSONPath — XPath for JSON, https://goessner.net/articles/JsonPath.
  3. Douglas Crockford — https://www.crockford.com/mckeeman.html
Topics:
gson, jackson, java, json, json to java object, jsonpath

Published at DZone with permission of Puneet Sapra . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}