REST
restapi4JsonHandling
- Path
- pkg12restapi/restapi4JsonHandling.java
- Package
- pkg12restapi
- Study order
- 4
- Run
- Single-file source launch
- Command
- java pkg12restapi/restapi4JsonHandling.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg12restapi;2 3import java.util.LinkedHashMap;4import java.util.List;5import java.util.Map;6 7/*8 * restapi4JsonHandling.java9 * -------------------------10 * Working with JSON. Real apps use Jackson or Gson; here we show the shape of11 * JSON and a tiny hand-rolled writer/reader so the demo has NO dependencies.12 *13 * DEFINITION:14 * JSON is the lingua franca of REST: objects {key:value}, arrays [..], strings,15 * numbers, booleans, null. In production, map JSON <-> POJOs with a library16 * (Jackson's ObjectMapper). This file demonstrates both worlds.17 *18 * KEY POINTS:19 * - Production: ObjectMapper.writeValueAsString(obj) / readValue(json, Pojo.class).20 * - Always escape special chars (" \\ newlines) when writing JSON by hand.21 * - Prefer a library for anything beyond trivial payloads — parsing is fiddly.22 * - Records map cleanly to/from JSON objects.23 */24public class restapi4JsonHandling {25 26 record User(int id, String name, boolean active) {}27 28 public static void main(String[] args) {29 // --- Build JSON from a record (toy serializer) ---30 User user = new User(1, "Ada \"the\" Lovelace", true);31 System.out.println("Serialized object:");32 System.out.println(" " + toJson(user));33 34 // --- Build a JSON array from a list ---35 List<User> users = List.of(new User(1, "Ada", true), new User(2, "Linus", false));36 StringBuilder arr = new StringBuilder("[");37 for (int i = 0; i < users.size(); i++) {38 if (i > 0) arr.append(',');39 arr.append(toJson(users.get(i)));40 }41 arr.append(']');42 System.out.println("\nSerialized array:");43 System.out.println(" " + arr);44 45 // --- Parse a flat JSON object into a Map (toy parser) ---46 String json = "{\"id\": 42, \"name\": \"Grace\", \"active\": false}";47 Map<String, String> parsed = parseFlat(json);48 System.out.println("\nParsed object:");49 parsed.forEach((k, v) -> System.out.println(" " + k + " = " + v));50 51 System.out.println("\nIn production, replace these helpers with Jackson:");52 System.out.println(" ObjectMapper m = new ObjectMapper();");53 System.out.println(" String s = m.writeValueAsString(user);");54 System.out.println(" User u = m.readValue(s, User.class);");55 }56 57 /** Minimal JSON object writer for a User record (escapes quotes/backslashes). */58 static String toJson(User u) {59 return "{\"id\":" + u.id()60 + ",\"name\":\"" + escape(u.name()) + "\""61 + ",\"active\":" + u.active() + "}";62 }63 64 static String escape(String s) {65 return s.replace("\\", "\\\\").replace("\"", "\\\"")66 .replace("\n", "\\n").replace("\t", "\\t");67 }68 69 /** Toy parser for a flat {"k": v, ...} object — NOT for nested/real JSON. */70 static Map<String, String> parseFlat(String json) {71 Map<String, String> out = new LinkedHashMap<>();72 String body = json.trim().replaceAll("^\\{|}$", "");73 for (String pair : body.split(",")) {74 String[] kv = pair.split(":", 2);75 if (kv.length == 2) out.put(clean(kv[0]), clean(kv[1]));76 }77 return out;78 }79 80 static String clean(String s) { return s.trim().replaceAll("^\"|\"$", ""); }81}