Write simple JSON text by hand
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)JSON (JavaScript Object Notation) is the text format that web apps, mobile apps and APIs use to send data to each other. It can hold nested data, like a student with a list of marks, which a flat CSV row cannot, and for small outputs you can write it with plain Java strings.
The shape of JSON: objects, arrays, values
JSON is a plain-text format for structured data: objects of key-value pairs, arrays, strings, numbers, true, false and null. Many programs and websites use it to exchange data.
A JSON object is a set of key-value pairs inside curly braces: {"roll": 101, "name": "Asha"}. Keys are always text in double quotes. A JSON array is an ordered list inside square brackets: [87, 92, 78].
Example 1 · One student as a JSON document
public class JsonShapeDemo { public static void main(String[] args) { String json = """ { "roll": 101, "name": "Asha Rao", "hostel": true, "mentor": null, "marks": [87, 92, 78], "address": { "city": "Pune", "pin": "411001" } }"""; System.out.println(json); System.out.println("Characters: " + json.length()); }}{
"roll": 101,
"name": "Asha Rao",
"hostel": true,
"mentor": null,
"marks": [87, 92, 78],
"address": {
"city": "Pune",
"pin": "411001"
}
}
Characters: 160What this code does
- One object holds every kind of value: a number, a string,
true,null, an array of numbers and another object for the address. - The PIN code is a string, not a number: it is an identifier that might start with 0, not a quantity you add up. Choosing the value type is part of designing JSON.
A value is one of six kinds: a string in double quotes, a number such as 87 or 78.5, true or false, null, an object or an array. Objects and arrays can hold each other, so data can be nested as deep as needed. JSON is strict. Single quotes, keys without quotes, a comma after the last item and comments are all invalid, even though JavaScript code allows some of them. A program that reads JSON rejects the whole document for one such mistake.
Building JSON with text blocks and StringBuilder
For a fixed shape, a text block (three double quotes, Java 15) with formatted is the clearest way: the JSON in the code looks exactly like the output.
Example 2 · A text block with formatted for a fixed shape
record Student(int roll, String name, boolean hostel, double average) {}
public class TextBlockJsonDemo { static String jsonString(String s) { if (s == null) { return "null"; } StringBuilder sb = new StringBuilder("\""); for (char c : s.toCharArray()) { switch (c) { case '"' -> sb.append("\\\""); case '\\' -> sb.append("\\\\"); case '\n' -> sb.append("\\n"); case '\r' -> sb.append("\\r"); case '\t' -> sb.append("\\t"); default -> { if (c < 0x20) { sb.append(String.format("\\u%04x", (int) c)); // other control characters } else { sb.append(c); } } } } return sb.append('"').toString(); }
static String toJson(Student s) { return """ {"roll": %d, "name": %s, "hostel": %b, "average": %s}""" .formatted(s.roll(), jsonString(s.name()), s.hostel(), String.valueOf(s.average())); }
public static void main(String[] args) { System.out.println(toJson(new Student(101, "Asha Rao", true, 85.5))); System.out.println(toJson(new Student(102, "Bhavesh Patel", false, 64.0))); }}{"roll": 101, "name": "Asha Rao", "hostel": true, "average": 85.5}
{"roll": 102, "name": "Bhavesh Patel", "hostel": false, "average": 64.0}What this code does
%sfor the name has no quotes around it in the template, becausejsonStringreturns the value already quoted and escaped.%bwritestrueorfalsewithout quotes.String.valueOf(double)always writes a dot, whatever the computer's locale, so85.5stays a valid JSON number.
Example 3 · A StringBuilder loop with commas only between items
import java.util.List;
record Item(String name, int qty, int price) {}
public class JsonArrayDemo { static String jsonString(String s) { if (s == null) { return "null"; } StringBuilder sb = new StringBuilder("\""); for (char c : s.toCharArray()) { switch (c) { case '"' -> sb.append("\\\""); case '\\' -> sb.append("\\\\"); case '\n' -> sb.append("\\n"); case '\r' -> sb.append("\\r"); case '\t' -> sb.append("\\t"); default -> { if (c < 0x20) { sb.append(String.format("\\u%04x", (int) c)); // other control characters } else { sb.append(c); } } } } return sb.append('"').toString(); }
static String toJson(List<Item> items) { StringBuilder sb = new StringBuilder("[\n"); for (int i = 0; i < items.size(); i++) { Item it = items.get(i); sb.append(" {\"name\": ").append(jsonString(it.name())) .append(", \"qty\": ").append(it.qty()) .append(", \"price\": ").append(it.price()).append("}"); if (i < items.size() - 1) { sb.append(","); // a comma only between items } sb.append("\n"); } return sb.append("]").toString(); }
public static void main(String[] args) { List<Item> order = List.of(new Item("Pen", 2, 15), new Item("Ruler", 3, 10), new Item("Bag", 1, 20)); System.out.println(toJson(order)); System.out.println(toJson(List.of())); }}[
{"name": "Pen", "qty": 2, "price": 15},
{"name": "Ruler", "qty": 3, "price": 10},
{"name": "Bag", "qty": 1, "price": 20}
]
[
]What this code does
- The check
i < items.size() - 1adds a comma after every item except the last. A comma after the last item would make many JSON readers reject the whole document. - An empty list still gives valid JSON: an empty array
[]with a line break inside. Always test the empty case of a loop that writes separators.
For a list of unknown length, use a StringBuilder loop. The trap is the comma: it goes between items, never after the last one. Add it before every item except the first, or use String.join(",", items).
Put %s for a string value with no quotes of your own around it: the escaped string already carries its quotes, as the next section shows. Numbers and true/false are written without quotes. For decimal numbers use String.valueOf(x) or Locale.ROOT, never the default locale, for the same reason as in CSV: 78,5 is not a JSON number.
Escaping quotes, backslashes and new lines
Inside a JSON string, " ends the string. So a value with a double quote, like Neel "Sonu" Shah, must be written as Neel \"Sonu\" Shah. This is escaping, and JSON uses the backslash for it, just like Java string literals.
Example 4 · Broken versus escaped strings
public class JsonEscapeDemo { static String jsonString(String s) { if (s == null) { return "null"; } StringBuilder sb = new StringBuilder("\""); for (char c : s.toCharArray()) { switch (c) { case '"' -> sb.append("\\\""); case '\\' -> sb.append("\\\\"); case '\n' -> sb.append("\\n"); case '\r' -> sb.append("\\r"); case '\t' -> sb.append("\\t"); default -> { if (c < 0x20) { sb.append(String.format("\\u%04x", (int) c)); // other control characters } else { sb.append(c); } } } } return sb.append('"').toString(); }
public static void main(String[] args) { String nickname = "Neel \"Sonu\" Shah"; String folder = "C:\\fest\\photos"; String note = "Line one\nLine two";
System.out.println("Naive:"); System.out.println("{\"name\": \"" + nickname + "\"}"); System.out.println("{\"folder\": \"" + folder + "\"}"); System.out.println("{\"note\": \"" + note + "\"}");
System.out.println("Escaped:"); System.out.println("{\"name\": " + jsonString(nickname) + "}"); System.out.println("{\"folder\": " + jsonString(folder) + "}"); System.out.println("{\"note\": " + jsonString(note) + "}"); System.out.println("{\"mentor\": " + jsonString(null) + "}"); }}Naive:
{"name": "Neel "Sonu" Shah"}
{"folder": "C:\fest\photos"}
{"note": "Line one
Line two"}
Escaped:
{"name": "Neel \"Sonu\" Shah"}
{"folder": "C:\\fest\\photos"}
{"note": "Line one\nLine two"}
{"mentor": null}What this code does
- In the naive output, the quote before
Sonuends the string early, in the folder a JSON reader takes\fas a form-feed character and\pis not a valid escape at all, and the note is split over two lines, which a JSON string may not be. All three are broken JSON. jsonStringwrites\",\\and\n, so every value survives, and a Javanullbecomes the JSON literalnullwithout quotes.
Four characters must always be escaped: the double quote as \", the backslash as \\ (think of a Windows path), a new line as \n and a tab as \t. Other invisible control characters are written as \u with four hex digits. Put the rules in one method, jsonString(String s), that returns the value already escaped and wrapped in quotes. Never build JSON with "\"" + name + "\"": it works for every test name until a real user types a quote.
Why real projects use a JSON library
Hand-written JSON is fine for a few fixed fields, such as a small status message or a test. As soon as the data grows, a library is safer: it escapes every string, places every comma and handles null, dates and nested lists for you.
Reading JSON by hand is much harder than writing it: nesting, escapes, numbers in many forms and missing keys all need care. A library such as Jackson or Gson turns JSON text into your records and back in one line each, and is tested on millions of documents.
Use your own code to learn the format and for tiny outputs. In a real project, add a JSON library with your build tool, Maven or Gradle, and let it do the work.
- By hand: small fixed shapes, tests, learning, no extra library allowed.
- Library: lists of records, nested data, dates, anything you must also read back.
- Never by hand: parsing JSON that comes from users or other programs.
Example 5 · Export a class list to students.json
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.ArrayList;import java.util.List;
record Student(int roll, String name, List<Integer> marks) { String toJson() { List<String> m = new ArrayList<>(); for (int x : marks) { m.add(String.valueOf(x)); } return "{\"roll\": " + roll + ", \"name\": " + ExportJsonDemo.jsonString(name) + ", \"marks\": [" + String.join(", ", m) + "]}"; }}
public class ExportJsonDemo { static String jsonString(String s) { if (s == null) { return "null"; } StringBuilder sb = new StringBuilder("\""); for (char c : s.toCharArray()) { switch (c) { case '"' -> sb.append("\\\""); case '\\' -> sb.append("\\\\"); case '\n' -> sb.append("\\n"); case '\r' -> sb.append("\\r"); case '\t' -> sb.append("\\t"); default -> { if (c < 0x20) { sb.append(String.format("\\u%04x", (int) c)); // other control characters } else { sb.append(c); } } } } return sb.append('"').toString(); }
public static void main(String[] args) throws IOException { List<Student> students = List.of( new Student(101, "Rao, Asha", List.of(87, 92)), new Student(102, "Neel \"Sonu\" Shah", List.of(64)), new Student(103, "Chitra", List.of()));
List<String> objects = new ArrayList<>(); for (Student s : students) { objects.add(" " + s.toJson()); } String json = "{\n \"class\": " + jsonString("CSE-A") + ",\n \"students\": [\n" + String.join(",\n", objects) + "\n ]\n}";
Path file = Path.of("students.json"); Files.writeString(file, json, StandardCharsets.UTF_8); System.out.println(Files.readString(file, StandardCharsets.UTF_8)); System.out.println("Saved " + students.size() + " students to " + file.getFileName()); Files.deleteIfExists(file); }}{
"class": "CSE-A",
"students": [
{"roll": 101, "name": "Rao, Asha", "marks": [87, 92]},
{"roll": 102, "name": "Neel \"Sonu\" Shah", "marks": [64]},
{"roll": 103, "name": "Chitra", "marks": []}
]
}
Saved 3 students to students.jsonWhat this code does
- Each record writes itself with
toJson, andString.join(",\n", ...)puts commas only between the objects. Chitra's empty marks list becomes[], which is valid. - The comma in
Rao, Ashaneeds no escaping in JSON, unlike CSV; only the quotes in Neel's name do. The file is saved as UTF-8, which is the standard encoding for JSON.
Next step
Check your understanding
12 quick questions