Skip to the content.

Introduction to JSON

-

What Is It?

JSON is a lightweight data-interchange format.
JSON stands for JavaScript Object Notation.
The syntax was inspired by the object literals of JavaScript 1.

-

Why JSON?

-

XML

Prior to JSON, XML was considered to be the chosen data-interchange format.

-

XML Example

<?xml version="1.0 encoding=UTF-8"?>
<students>
    <student>
        <studentid>101</studentid>
        <firstname>John</firstname>
        <lastname>Doe</lastname>
        <classes>
            <class>Business Research</class>
            <class>Economics</class>
            <class>Finance</class>
        </classes>
    </student>
    <student>
    <studentid>102</studentid>
        <firstname>Jane</firstname>
        <lastname>Dane</lastname>
        <classes>
            <class>Marketing</class>
            <class>Economics</class>
            <class>Finance</class>
        </classes>
    </student>
</students>

-

JSON Example

{
    "students": {
        "0": {
            "studentid": 101,
            "firstname": "John",
            "lastname": "Doe",
            "classes": [
                "Business Research",
                "Economics",
                "Finance",
            ]
        },
        "1": {
            "studentid": 102,
            "firstname": "Jane",
            "lastname": "Dane",
            "classes": [
                "Marketing",
                "Economics",
                "Finance",
            ]
        }
    }
}

-

Datatypes In JSON

-

Types Examples

JSON supports the following data structures.

-

Objects

An object is an unordered set of name/value pairs.

{
    "key1": "value1",
    "key2": "value2",
}

-

String

Strings in JSON must be written in double quotes.

{
    "carId": "AZU-3005",
    "carMake": "Chevy",
    "carModel": "Camaro",
}

-

Numbers

Numbers in JSON must be an integer or a floating point.

{
    "modelYear": 1967,
    "acceleration060": 6.3,
}

-

Booleans

Values in JSON can be true/false.

{
    "isForSale": false,
    "isAntique": true,
}

-

Null

Values in JSON can be null.

{
    "serviceHistory": null
}

-

Arrays

An array is an ordered collection of values.

-

Arrays Example 1

{
    "serviceHistory": [],
}

-

Arrays Example 2

{
    "serviceHistory": [
        "Sep 06 1968",
        "Jun 23 1968",
    ]
}

-

Arrays Example 3

{
    "serviceHistory": [
        {
            "serviceType": "Oil change",
            "serviceDate": "Sep 06 1968"
        },
        {
            "serviceType": "Tire repair",
            "serviceDate":  "Jun 23 1968",
        }  
    ]
}

-

Python’s JSON module

-

What Is It?

The Python Standard Library provides the json module for working with JSON data.

import json

-

How Does It Work?

Python JSON
dict object
list, tuple array
str string
int, float, int- & float-derived Enums number
True true
False false
None null

-

JSON to Dict

json.loads()

import json

person_as_json = '{"name": "bob", "age": 18, "activeCustomer": true, "investments": null}'

person_as_dict = json.loads(person_as_json)
person_as_dict
# {'name': 'bob', 'age': 18, 'activeCustomer': True, 'investments': None}

type(person_as_dict)
# <class 'dict'>

-

Dict To JSON

json.dumps()

import json

person_as_dict = {'name': 'bob', 'age': 18, 'activeCustomer': True, 'investments': None}

person_as_json = json.dumps(person_as_dict)
person_as_json
# '{"name": "bob", "age": 18, "activeCustomer": true, "investments": null}'
type(person_as_json)
# <class 'str'>

-

List to JSON

json.dumps()

import json

animals_as_list = ['dog', 'cat', 'mouse']
animals_as_json = json.dumps(animals_as_list)
type(animals_as_json)
# <class 'str'>

-

JSON to List

import json

numbers_as_json = '[1, 2, 3, 4]'
numbers_as_list = json.loads(numbers_as_json)
numbers_as_list
# [1, 2, 3, 4]

-

JSON and Java (Jackson)

-

JSON and Java (Jackson)

Jackson is a high-performance JSON processing library for Java that provides three main components:

-

Jackson Dependency:

To get the Jar for Jackson added your project:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.16.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.16.0</version>
</dependency>

-

Basic Usage of Jackson: Streaming API

-

Basic Usage of Jackson: Streaming API

Using the streaming API involves creating a JsonParser to read and a JsonGenerator to write:

JsonFactory jsonFactory = new JsonFactory();// Create JsonFactory

// Writing JSON using JsonGenerator
try (JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream)) {
    jsonGenerator.writeStartObject();
    jsonGenerator.writeStringField("name", "Jawn Dough");
    jsonGenerator.writeNumberField("age", 27);
    jsonGenerator.writeEndObject();
}

// Reading JSON using JsonParser
try (JsonParser jsonParser = jsonFactory.createParser(jsonString)) {
    while (!jsonParser.isClosed()) {
        jsonParser.nextToken();
        // Process JSON tokens
    }
}

-

Basic Usage of Jackson: Data Binding

-

Basic Usage of Jackson: Data Binding

To use Jackson for serialization and deserialization, you typically create an instance of ObjectMapper:


// Create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();

// Serialize an object to JSON
String jsonString = objectMapper.writeValueAsString(myObject);

// Deserialize JSON to an object
MyClass deserializedObject = objectMapper.readValue(jsonString, MyClass.class);

* Note: To effectively serialize/deserialize, you will need to make sure the mapped object’s Class has a NULLARY CONSTRUCTOR! -

Basic Usage of Jackson: Tree Model

-

Basic Usage of Jackson: Tree Model

Using the tree model involves creating a JsonNode:

// Create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();

// Create a JsonNode from a JSON string
JsonNode jsonNode = objectMapper.readTree(jsonString);

// Accessing values from JsonNode
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();

These are just basic examples, and Jackson provides many more features and customization options. Whether you’re working with simple JSON structures or complex nested objects, Jackson is a powerful tool for handling JSON in Java.

-

PupDuckSweater