JSON
On This Lesson 11 topics
Lesson Overview
The restaurant's dish needs a plate: a shape in which the food reaches you. When a server sends data to a program rather than a person, that plate is usually JSON (JavaScript Object Notation), a small text format for describing data. The Content-Type: application/json header from the last lesson announces it.
JSON is popular because it is plain text, easy for people to read, and easy for programs in any language to produce and parse. As a Java backend developer you will read JSON in requests and write it in responses all day, so it is worth being fluent: knowing the six kinds of value, the strict punctuation rules, and how a JSON object lines up with a Java class.
This lesson builds on lesson 4 (Content-Type) and on the Java classes, fields, and List from earlier modules.
Learning Objectives
By the end of this lesson you will be able to:
- Name the six JSON value types: object, array, string, number, boolean, and
null. - Write valid JSON for a record with text, numbers, booleans, a list, and a nested object.
- Spot the common syntax errors: unquoted keys, single quotes, trailing commas, comments.
- Map JSON to Java mentally: object to class, array to
List, string toString, number tointordouble, boolean toboolean,nulltonull. - Read a nested JSON path such as the second phone of a member.
- Explain why JSON can be sent over HTTP: it is just text.
Written Explanation
What JSON looks like
{
"id": 7,
"title": "Dune",
"authors": ["Frank Herbert"],
"available": true,
"isbn": null
}This is one object: a collection of name/value pairs in curly braces. The names (also called keys) are strings; each is followed by a colon and a value; pairs are separated by commas.
The six kinds of value
RFC 8259, the JSON standard, lists the value types. In plain terms:
| Type | Written like | Example |
|---|---|---|
| Object | { "name": value, ... } | {"city":"Riyadh"} |
| Array | [ value, value, ... ] | ["a","b"] |
| String | text in double quotes | "Dune" |
| Number | digits, optional minus, fraction, exponent | 7, -2, 3.5 |
| Boolean | true or false (lower case) | true |
| Null | null (lower case) | null |
Objects and arrays can contain any values, including more objects and arrays, so structures can be nested as deep as needed. Arrays are ordered; an array may mix types, though in practice one array usually holds one kind of thing.
The strict rules
JSON looks like programming-language syntax but is stricter. MDN and the RFC agree on these:
- Keys and strings use double quotes.
{name: "Ana"}and{'name': 'Ana'}are invalid. - No trailing commas.
{"a":1,}is invalid. Commas go only between items. - No comments. JSON has no comment syntax.
- Numbers are plain decimal.
NaN,Infinity, andundefineddo not exist. The RFC also forbids leading zeros such as030. true,false, andnullare lower case.
A single misplaced comma makes the whole text invalid, so a parser throws an error rather than guessing. The RFC also says JSON sent between systems must be encoded in UTF-8, the text encoding you met earlier, which is why it works for names in many languages.
Mapping JSON to Java
A Java class describes the shape of one kind of thing; a JSON object is one instance of it. The mapping is natural:
| JSON | Java |
|---|---|
| object | class (each key becomes a field) |
| array | List<...> (or an array) |
| string | String |
| whole number | int or long |
| decimal number | double |
true / false | boolean |
null | null (so use a reference type such as String, not int) |
For the book above:
class Book {
int id;
String title;
List<String> authors;
boolean available;
String isbn; // can be null
}In later modules you will use a library to convert between JSON text and objects automatically (this is called serialization and deserialization, or "marshalling"). For now it is a mental exercise: you should be able to look at JSON and see the class, and look at a class and write the JSON.
A nested object is a field whose type is another class. A member with an address object and a list of phones looks like this:
{
"name": "Ana",
"age": 30,
"active": true,
"nickname": null,
"address": { "city": "Riyadh", "street": "Main St" },
"phones": ["555-0101", "555-0102"]
}To reach the second phone you follow the path phones, then position 1 (arrays count from zero, as in Java).
Examples
Example 1: Valid or invalid? (simple)
| Text | Valid? | Why |
|---|---|---|
{"name":"Ana"} | Yes | |
{name:"Ana"} | No | Key is not in double quotes |
{'name':'Ana'} | No | Single quotes |
{"a":1,"b":2,} | No | Trailing comma |
[1,2,3] | Yes | A top-level array is valid JSON |
{"ok":True} | No | true must be lower case |
(All verdicts follow from the RFC grammar and MDN rules above; I did not run a JSON parser to confirm them.)
Example 2: From class to JSON (practical)
The Java object below is built and printed with a hand-written method that produces JSON text. This is only to make the correspondence visible; you will not do this by hand in real projects.
import java.util.List;
public class L05 {
static class Book {
int id = 7;
String title = "Dune";
List<String> authors = List.of("Frank Herbert");
boolean available = true;
String toJson() {
StringBuilder sb = new StringBuilder("{");
sb.append("\"id\":").append(id).append(",");
sb.append("\"title\":\"").append(title).append("\",");
sb.append("\"authors\":[");
for (int i = 0; i < authors.size(); i++) {
if (i > 0) sb.append(",");
sb.append("\"").append(authors.get(i)).append("\"");
}
sb.append("],");
sb.append("\"available\":").append(available).append("}");
return sb.toString();
}
}
public static void main(String[] args) {
System.out.println(new Book().toJson());
}
}Output (compiled and run with JDK 21):
{"id":7,"title":"Dune","authors":["Frank Herbert"],"available":true}The int and boolean fields became bare numbers and true, the String got quotes, and the List became an array in square brackets. Writing it by hand also shows the pain: quotes inside quotes, commas to place. That is why libraries do it, and why hand-built JSON strings are fragile (for instance, a title containing a double quote would break this method).
Example 3: Nested data and null in Java (realistic)
Here is the Member JSON from above as Java classes, filled in by hand:
import java.util.List;
public class L05b {
static class Address {
String city;
String street;
Address(String city, String street) { this.city = city; this.street = street; }
}
static class Member {
String name;
int age;
boolean active;
String nickname; // may be null
Address address; // JSON object inside JSON object
List<String> phones; // JSON array of strings
}
public static void main(String[] args) {
Member m = new Member();
m.name = "Ana";
m.age = 30;
m.active = true;
m.nickname = null;
m.address = new Address("Riyadh", "Main St");
m.phones = List.of("555-0101", "555-0102");
System.out.println(m.name + " " + m.age + " " + m.active + " " + m.nickname);
System.out.println(m.address.city + " / " + m.phones.get(1) + " / " + m.phones.size());
}
}Output (compiled and run with JDK 21):
Ana 30 true null
Riyadh / 555-0102 / 2The JSON path address.city became m.address.city and phones[1] became m.phones.get(1). The null for nickname is a real null, so reading m.nickname.length() would throw a NullPointerException, a problem you met in the lesson on null. Real APIs use null or simply leave the key out to mean "no value".
Backend Insight
JSON is the usual body format for the APIs you will write in the Java web modules: a request arrives with a JSON body and Content-Type: application/json; your code turns it into Java objects, does its work, and turns result objects back into JSON for the response.
Three practical habits. First, decide the shape of your JSON as carefully as you design a class, because other programs will depend on it; renaming a key breaks every client. Second, never trust incoming JSON: it can be syntactically broken (answer 400), have missing keys (a field stays null), or have the wrong type (a string where a number belongs). Third, keep JSON for data and headers for metadata: put the book in the body, the format in Content-Type.
A reminder on money and precision: JSON has only one number type and does not say how big or precise it is; how the numbers are read is up to the receiving program. This is why real systems often send amounts as strings or whole cents; the details come later.
Common Mistakes
Mistake 1: Using single quotes or unquoted keys
- Incorrect:
{'name': 'Ana'}or{name: "Ana"}. - Correct:
{"name": "Ana"}.
Mistake 2: A trailing comma or a comment
- Incorrect:
{"a": 1, "b": 2,}and{"a": 1 // note}. - Correct:
{"a": 1, "b": 2}; keep notes outside the JSON.
Mistake 3: Writing numbers or booleans as strings by accident
- Incorrect:
{"age": "30", "active": "true"}when the class expects anintand aboolean. - Correct:
{"age": 30, "active": true}. Quotes make it a string.
Mistake 4: Forgetting that a field can be null
- Incorrect: assuming
nicknamealways has text and calling a method on it. - Correct: check for
nullfirst, or treat a missing key as "no value".
Exercises
Level A: Foundation
A1. Write JSON for a movie with a title, a release year, and a list of two genres.
Show solution A1
A1. Example: {"title":"Arrival","year":2016,"genres":["drama","science fiction"]}.
A2. Which are invalid, and why? {"a":1}, {a:1}, ["x","y",], {"flag":false}.
Show solution A2
A2. {a:1} is invalid (unquoted key). ["x","y",] is invalid (trailing comma). The other two are valid.
A3. Which Java type fits best for: a JSON array of strings; a JSON true; a JSON string?
Show solution A3
A3. List<String>; boolean; String.
Level B: Application
B1. Write the Java class that matches your movie JSON from A1.
Show solution B1
B1.
class Movie {
String title;
int year;
List<String> genres;
}B2. Given:
{"order": 55, "customer": {"name": "Sam"}, "items": [{"sku": "A1", "qty": 2}, {"sku": "B7", "qty": 1}]}What is the value at customer.name? What is the sku of the second item? How many items are there?
Show solution B2
B2. customer.name is "Sam". The second item's sku is "B7". There are 2 items.
B3. A client sends {"title": "Dune", "year": "1965"} where year is meant to be an int. What is wrong, and what should the server do?
Show solution B3
B3. "1965" is a string, not a number. The server should either reject the request with 400 and say that year must be a number, or deliberately convert it; silently guessing is risky. Answering 400 is the safer choice.
Level C: Challenge
C1. Design the JSON for a library loan: a loan id, the member (name and id), the book (title and id), a due date as text, and a returned flag. Then sketch the Java classes Loan, Member, and Book (fields only).
Show solution C1
C1. Example:
{
"id": 301,
"member": { "id": 12, "name": "Ana" },
"book": { "id": 7, "title": "Dune" },
"dueDate": "2026-12-01",
"returned": false
}class Member { int id; String name; }
class Book { int id; String title; }
class Loan {
int id;
Member member;
Book book;
String dueDate;
boolean returned;
}(The date is text because JSON has no date type. The class sketch is fields only and was not compiled.)
C2. Why can the following JSON not be parsed, and how many errors does it contain? {'id': 1, "tags": ["a", "b",], // first}
Show solution C2
C2. It has three errors: single quotes around 'id', a trailing comma after "b", and a comment // first. Also the closing brace is commented out, so the object is not even closed.
Mini Challenge
Choose something you own (a phone, a recipe, a pet). Write JSON describing it with at least: one string, one number, one boolean, one array, one nested object, and one null. Then write the Java class (or classes) that match it, and write one line of Java that reads a value from inside the nested object.
Check your work: every key and string is double-quoted, there are no trailing commas or comments, each JSON type is used once, and the Java types follow the mapping table.
Summary & Next Lesson
Key takeaways
- JSON is text for data with six value types: object, array, string, number, boolean, and
null. - Keys and strings need double quotes; no trailing commas, no comments.
- Object maps to a Java class, array to a
List, andnulltonull. - JSON travels in HTTP bodies, announced by
Content-Type: application/json. - Never trust incoming JSON: it may be broken, incomplete, or of the wrong type.
Next lesson
The next lesson, "URLs and query parameters", returns to the target of the request line and takes it apart: scheme, host, path, query, and fragment.
Self-check
- Which JSON type maps to a Java
List? - Is
{name: "Ana"}valid JSON? - Can JSON contain comments?
- How do you write "no value" in JSON?
- What header announces a JSON body?
Show answers
- An array.
- No: keys need double quotes, so it must be
{"name": "Ana"}. - No.
null.Content-Type: application/json.
References
- RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format. Supports the value types, double-quoted strings, number rules (no leading zeros, no NaN or Infinity), lower-case literals, the
application/jsonmedia type, and the UTF-8 requirement. Its grammar has no comments or trailing commas. - MDN: Working with JSON. Supports the strict syntax rules with valid and invalid examples: quoted keys, double quotes only, no trailing commas, no comments.
Not verified from a source: the advice about sending money as strings or whole cents is common practice, not quoted from a standard.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.