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
- Understand what JSON is and why we use it over other data formats like XML
- See API communication with JSON responses
- Gain a high-level overview of using GSON as a serialization library
- Understand fetching JSON data from an API, deserializing it with GSON, and displaying a formatted message in the terminal
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:
- Numbers (integers or floating-point)
- Strings (enclosed in double quotes)
- Booleans (true or false)
- null
- Arrays (ordered list of values)
- Objects (unordered collection of key-value pairs)
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(); } } }
Mastery Task 3: JSON Repositories
Mastery Task Guidelines
Mastery Tasks are opportunities to test your knowledge and understanding through code. When a mastery task is shown in a module, it means that we've covered all the concepts that you need to complete that task.
Each mastery task must pass 100% of the automated tests and code styling checks to pass each sprint. Your code must be your own. If you have any questions, feel free to reach out for support.
Implementing the Repositories
We are getting closer to using real databases in this course. In this project we take one step closer, reading and writing to .json files. By maintaining the JSON format in these files, we can use a transpiler such as GSON to convert between text files and strings to useable Java objects.
For any data layer, we want to restrict access to it by any means other than through a repository. We don't want other classes, or worse other coders, to try to read and write to our database, instead we write a single repository and require database requests to pass through it instead.
Our repositories will need to use file i/o and the GSON library to parse our objects to and from JSON, and then store that info in the PostData.json and UserData.json files inside the resource directory.
Implement the User Repository save Method
Some of the logic has been implemented for you. We can see that we first attempt to getAllUsers so that we have a list of all existing users. This is for two reasons:
- So that we can check if the new User we are trying to add already exists (this has been implemented for you).
- Because when we write to the UserData.json file, we are going to replace the entire file with the updated list of users as opposed to trying to append a new user into the list. (You can see already what kinds of features a real database might have figured out for us already).
What's left is for you to convert this list of users into JSON and write it to the UserData.json file.
HINT: You should use Gsons setPrettyPrint() method to pretty-print the JSON in the file.
When you have completed this task, run the App class which calls on the SeedData to run. If you check the UserData.json file after this you will see you have one user's data. (Why is it only one?)
Implement the getAllUsers Method
Now that we have some data in the UserData.json file, we can try to get that data back. Right now this method returns an empty array. Implement the logic to read the UserData file, convert the resulting String into a list of User objects, and return that list.
When you are done, if you run the App main method again, the UserData.json file will now have all three User's data.
Implement the PostRepository methods
This repository should follow similar logic to the UserRepository.
Completion
When you are done all of the tests in the MT03_JsonReadWrite class should pass:
./gradle -q clean :test --tests 'com.bloomtech.socialfeed.MT03*'