DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • FHIR Data Model With Couchbase N1QL
  • NFT Wallets Unleashed: A Data Structures and Application Design Journey
  • JSON-Based Serialized LOB Pattern
  • JSON Minify Full Guideline: Easy For You

Trending

  • Agentic AI for Automated Application Security and Vulnerability Management
  • Why Database Migrations Take Months and How to Speed Them Up
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  1. DZone
  2. Data Engineering
  3. Data
  4. Patterns of Reading JSON

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).

By 
Puneet Sapra user avatar
Puneet Sapra
·
Jun. 24, 20 · Opinion
Likes (3)
Comment
Save
Tweet
Share
14.4K Views

Join the DZone community and get the full member experience.

Join For Free

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 abstract. JSON 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
xxxxxxxxxx
1
22
 
1
{
2
   "destination_addresses" : [ "New York, NY, USA" ],
3
   "origin_addresses" : [ "Washington, DC, USA" ],
4
   "rows" : [
5
      {
6
         "elements" : [
7
            {
8
               "distance" : {
9
                  "text" : "225 mi",
10
                  "value" : 361715
11
               },
12
               "duration" : {
13
                  "text" : "3 hours 49 mins",
14
                  "value" : 13725
15
               },
16
               "status" : "OK"
17
            }
18
         ]
19
      }
20
   ],
21
   "status" : "OK"
22
}


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

Java
xxxxxxxxxx
1
 
1
JsonParser parser = new JsonParser();
2
// tree object structure is provided by lib.
3
JsonElement parsedTree = parser.parse(json);
4
JsonObject root = parsedTree.getAsJsonObject();
5
JsonObject firstRow = root.get("rows").getAsJsonArray().get(0).getAsJsonObject();
6
JsonObject firstElement = firstRow.get("elements").getAsJsonArray().get(0).getAsJsonObject();
7
8
// finally, distance is extracted ! Phew 
9
String distance = firstElement.get("distance").getAsJsonObject().get("value").getAsString();
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
xxxxxxxxxx
1
10
 
1
{
2
 "created_at": "Wed Oct 10 20:19:24 +0000 2018",
3
 "id": 1050118621198921728,
4
 "id_str": "1050118621198921728",
5
 "text": "To make room for more expression, we will now count all emojis as equal—including those with gender and skin t… https://t.co/MkGjXf9aXm",
6
 "user": {...}
7
.
8
.
9
.
10
}


The equivalent class would be for the above JSON:

Java
xxxxxxxxxx
1
10
 
1
class Tweet {
2
3
  private long id;
4
  private String id_str;
5
  private String text;
6
  private String source;
7
  private User user;
8
  private String created_at;
9
10
}

JSON
xxxxxxxxxx
1
11
 
1
{ "user": {
2
    "id": 6253282,
3
    "id_str": "6253282",
4
    "name": "Twitter API",
5
    "screen_name": "TwitterAPI",
6
    "location": "San Francisco, CA",
7
    "url": "https://developer.twitter.com",
8
    "description": "The Real Twitter API. Tweets about API changes, service issues and our Developer Platform. Don't get an answer? It's on my website."
9
.
10
 }
11
}
Java
xxxxxxxxxx
1
11
 
1
class User {
2
3
  private long id;
4
  private String id_str;
5
  private String name;
6
  private String description;
7
  private String screen_name;
8
  private String url;
9
  private String location;
10
11
}


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
xxxxxxxxxx
1
 
1
ObjectMapper objectMapper = new ObjectMapper();
2
Tweet tweet = objectMapper.readValue(tweetAsJson, Tweet.class);
3
4
// process Tweet object
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
xxxxxxxxxx
1
22
 
1
{
2
   "destination_addresses" : [ "New York, NY, USA" ],
3
   "origin_addresses" : [ "Washington, DC, USA" ],
4
   "rows" : [
5
      {
6
         "elements" : [
7
            {
8
               "distance" : {
9
                  "text" : "225 mi",
10
                  "value" : 361715
11
               },
12
               "duration" : {
13
                  "text" : "3 hours 49 mins",
14
                  "value" : 13725
15
               },
16
               "status" : "OK"
17
            }
18
         ]
19
      }
20
   ],
21
   "status" : "OK"
22
}


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

Java
xxxxxxxxxx
1
 
1
ReadContext ctx = JsonPath.parse(distanceJson);
2
Double distance = ctx.read("$.rows[0].elements[0].distance.value", Double.class);
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
xxxxxxxxxx
1
 
1
{
2
  "name": "Mighty",
3
  "handler": "DM8typrogrammer"
4
}


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
xxxxxxxxxx
1
24
 
1
String json = "{\"name\": \"mighty\", \"handler\": \"DM8typrogrammer\"}";
2
JsonFactory jsonfactory = new JsonFactory();
3
JsonParser jsonParser = jsonfactory.createParser(json);
4
 
          
5
// putting values in map
6
Map<String, String> data = new HashMap<>();
7
 
          
8
JsonToken currentToken = jsonParser.nextToken();
9
while (currentToken != JsonToken.END_OBJECT) {
10
  
11
  if (currentToken == JsonToken.FIELD_NAME) {
12
    String fieldname = jsonParser.getCurrentName();
13
    jsonParser.nextToken(); // move to value
14
    
15
    // pushing data to map
16
    data.put(fieldname, jsonParser.getText());    
17
  }
18
 
          
19
  // iterating token by token
20
  currentToken = jsonParser.nextToken();
21
}
22
jsonParser.close();
23
 
          
24
System.out.println(data);
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
JSON Data structure Object (computer science) Data (computing) Web API Binding (linguistics)

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

Opinions expressed by DZone contributors are their own.

Related

  • FHIR Data Model With Couchbase N1QL
  • NFT Wallets Unleashed: A Data Structures and Application Design Journey
  • JSON-Based Serialized LOB Pattern
  • JSON Minify Full Guideline: Easy For You

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!