← Back to Home

Module 3: Introduction to JSON

Module Overview

Learn about JSON (JavaScript Object Notation), a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. Understand how to work with JSON in Java applications for data serialization and API communication.

Learning Objectives

JSON Fundamentals

JSON is a data format used to store and exchange data in a human-readable format. It's a text format that is language-independent but uses conventions familiar to programmers of the C-family of languages. JSON is commonly used for transmitting data in web applications and APIs.

JSON Data Types

JSON supports the following data types:

Example JSON Document

{
  "name": "John Doe",
  "age": 43,
  "isEmployed": true,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA"
  },
  "children": [
    {
      "name": "Jane Doe",
      "age": 12,
      "children": null
    },
    {
      "name": "Jack Doe",
      "age": 10,
      "children": null
    }
  ]
}

Working with JSON in Java

Java provides several libraries for working with JSON. One of the most popular is Gson, developed by Google. Here's how you might use Gson to serialize and deserialize JSON:

// Add Gson dependency to your project
// implementation 'com.google.code.gson:gson:2.8.9'

import com.google.gson.Gson;

// Class to represent a person
class Person {
    private String name;
    private int age;
    private boolean isEmployed;
    
    // Constructor, getters, and setters...
}

// Serializing an object to JSON
Person person = new Person("John Doe", 43, true);
Gson gson = new Gson();
String json = gson.toJson(person);
System.out.println(json);
// Output: {"name":"John Doe","age":43,"isEmployed":true}

// Deserializing JSON to an object
String json = "{\"name\":\"John Doe\",\"age\":43,\"isEmployed\":true}";
Person person = gson.fromJson(json, Person.class);
System.out.println(person.getName()); // John Doe

Fetching JSON from an API

Here's an example of how to fetch JSON data from an API and process it with Gson:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class ApiExample {
    public static void main(String[] args) {
        try {
            // Create URL object
            URL url = new URL("https://api.example.com/data");
            
            // Open connection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            
            // Read response
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            
            // Parse JSON response
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(response.toString(), JsonObject.class);
            
            // Extract and use data
            String name = jsonObject.get("name").getAsString();
            int age = jsonObject.get("age").getAsInt();
            
            System.out.println("Name: " + name + ", Age: " + age);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Resources