Capstone 1: a JSON value
The last part of the course is three projects. The first is a JSON value: the model of the six things a JSON document is made of, a writer for them in the next lesson, and the tests and the packaging at the end. The project grows page by page, and each page is a program that builds and runs on its own.
The sealed interface
JSON has six forms: null, a number, a string, a boolean, an array and an object. That is a closed set, which is what a sealed interface of records is for: the compiler knows every form, a switch over the interface is exhaustive, and a function that adds a form forgets to handle it does not build.
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class JsonValue {
sealed interface Json permits JsonNull, JsonNumber, JsonString, JsonBool, JsonArray, JsonObject {
}
record JsonNull() implements Json {
}
record JsonNumber(double value) implements Json {
}
record JsonString(String value) implements Json {
}
record JsonBool(boolean value) implements Json {
}
record JsonArray(List<Json> values) implements Json {
}
record JsonObject(Map<String, Json> fields) implements Json {
}
static String kind(Json json) {
return switch (json) {
case JsonNull() -> "null";
case JsonNumber(double value) -> "number";
case JsonString(String value) -> "string";
case JsonBool(boolean value) -> "bool";
case JsonArray(List<Json> values) -> "array";
case JsonObject(Map<String, Json> fields) -> "object";
};
}
static boolean scalar(Json json) {
return switch (json) {
case JsonNull() -> true;
case JsonNumber(double v) -> true;
case JsonString(String v) -> true;
case JsonBool(boolean v) -> true;
case JsonArray(List<Json> values) -> false;
case JsonObject(Map<String, Json> fields) -> false;
};
}
static int size(Json json) {
return switch (json) {
case JsonArray(List<Json> values) -> values.size();
case JsonObject(Map<String, Json> fields) -> fields.size();
default -> 0;
};
}
public static void main(String[] args) {
Map<String, Json> fields = new LinkedHashMap<>();
fields.put("name", new JsonString("Ada"));
fields.put("age", new JsonNumber(36));
fields.put("admin", new JsonBool(true));
fields.put("nickname", new JsonNull());
Json user = new JsonObject(fields);
Json list = new JsonArray(List.of(new JsonNumber(1), new JsonNumber(2)));
System.out.println(user);
System.out.println("kind: " + kind(user) + " scalar: " + scalar(user) + " size: " + size(user));
System.out.println("kind: " + kind(list) + " scalar: " + scalar(list) + " size: " + size(list));
System.out.println("null equals itself: " + new JsonNull().equals(new JsonNull()));
Map<String, Json> reversed = new LinkedHashMap<>();
reversed.put("nickname", new JsonNull());
reversed.put("admin", new JsonBool(true));
reversed.put("age", new JsonNumber(36));
reversed.put("name", new JsonString("Ada"));
System.out.println("same fields equal: " + user.equals(new JsonObject(reversed)));
System.out.println("number 1 is not string 1: " + new JsonNumber(1).equals(new JsonString("1")));
}
}
javac -Xlint:all JsonValue.java
java JsonValue
JsonObject[fields={name=JsonString[value=Ada], age=JsonNumber[value=36.0], admin=JsonBool[value=true], nickname=JsonNull[]}]
kind: object scalar: false size: 4
kind: array scalar: false size: 2
null equals itself: true
same fields equal: true
number 1 is not string 1: false
The six forms
Two of the six hold nothing (JsonNull), a number, a string or a boolean, and the other two hold a collection of values: an array holds a list and an object holds a map. The map is a LinkedHashMap in the program for one reason: the order of the fields is the order a document shows, and Map.of does not keep it.
The two recursive forms are what makes the model a tree. A JSON document is a value, an array of values, or an object whose fields are values, and the type says exactly that. The records of lesson 055 carry the payload and the sealed interface of lesson 058 closes the set, and the two together are the model.
Total functions over the model
The three functions are the shape of every function the project will add. kind names the form, scalar says whether it is one value, and size counts the members of the two collections. Each switch names every permitted record and none has a default, so the compiler proves that all six are handled.
size is the one with a default, and the reason is a choice: a scalar has no size, and writing four cases that all answer zero is longer than the default. A default here is safe because the answer is the same for the four it covers, which is not true of a function that must decide something per form.
Equality for free
The last three lines are the records doing their work. A JsonNull equals another one because a record with no components is equal to every record of its type. Two objects with the same fields are equal although their maps were filled in a different order, because map equality compares the entries. And a number is never equal to a string, because the classes differ.
That equality is what the tests of lesson 135 rely on: a test that parses a document and compares it with an expected value does not need a comparison written by hand, and a failure prints both trees. The writer of the next lesson and the parser of the service are then checked against a model that compares itself.
What comes next
The model is the first half of the first capstone. The next lesson adds the writer: render, a switch over the same six forms that produces the text of a document, with the escaping rules of JSON for a string and the separators of an array and an object. The third lesson of the capstone is the tests, and they compare the text with what a reader expects.
Exercises
- Add a function that counts every value in the tree, arrays and objects included.
- Write a function that answers whether a document contains a given key at any depth.
- Make the object form reject a null key in its compact constructor.
- Try to add a seventh form and list the functions the compiler refuses.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is the JSON model a sealed interface?
Answer
The six forms are a closed set, so a switch over them can be exhaustive
The closed list is what lets the compiler check every function that switches on it.
-
Which two forms hold other values?
Answer
The array and the object
An array holds a list and an object a map, which is why the model is a tree.
-
Why does the object form take a LinkedHashMap in the program?
Answer
The order of the fields is the order a document shows
Map.of does not promise the order of its iteration, and a JSON document has one.
-
What does this program print?
public class Q1 { sealed interface V permits N, S { } record N(int value) implements V { } record S(String value) implements V { } static String kind(V value) { return switch (value) { case N(int n) -> "number"; case S(String s) -> "string"; }; } public static void main(String[] args) { System.out.println(kind(new N(1))); System.out.println(kind(new S("1"))); } }Answer
number / string
The switch picks the record type, and the two forms are handled separately.
-
Why does
sizeuse a default wherekinddoes not?Answer
The four forms it covers all answer zero, and the others decide per form
A default is safe when every covered form gives the same answer.
-
What does a record with no components compare equal to?
Answer
Every other record of the same type
Two JsonNull records have the same components, which are none.
-
Why is a number never equal to the string of the same digits?
Answer
Their records are different classes, and equals checks the type
The generated equals of a record starts with the runtime class, so the two forms never match.
-
What does this program print?
public class Q2 { record P(int x, int y) { } public static void main(String[] args) { System.out.println(new P(1, 2).equals(new P(1, 2))); System.out.println(new P(1, 2).hashCode() == new P(1, 2).hashCode()); } }Answer
true / true
The record compares and hashes its components, so both answers are true.
-
What happens when a seventh form is added to the sealed interface?
Answer
Every switch without a default stops compiling
The exhaustive switches are checked against the permitted list, which is the property the model is for.
-
Why is an object with the same fields in another order equal?
Answer
Map equality compares the entries and not the order
The two maps have the same keys and values, and a map has no order in its equality.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev