Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 11 / Topic 6 of 10

Parsing JSON: by hand, and why a library exists

The JDK ships no JSON parser at all — not even a basic one. Real projects add a library for this (Jackson or Gson are the two most common); this course does not install one, so the honest options for a flat JSON object are: pull fields out with regex (section 5's tool, pointed at JSON), or write a tiny hand-rolled parser. Both work for a flat object — no nested { } or [ ] inside it — and both quietly break the moment the JSON has any real structure. Think of reading a shopping receipt versus a nested invoice with sub-totals per department: scanning a flat receipt line by line for "item: price" works fine; the same scanning approach on a nested invoice has no way to know which department's sub-total it just read.

Pattern fieldPattern = Pattern.compile("\"(\\w+)\"\\s*:\\s*(\"([^\"]*)\"|-?\\d+(\\.\\d+)?|true|false|null)");
Matcher matcher = fieldPattern.matcher(json);
while (matcher.find()) {
    fields.put(matcher.group(1), matcher.group(3) != null ? matcher.group(3) : matcher.group(2));
}
$ javac JsonByHandDemo.java
$ java JsonByHandDemo
-- a flat object: by-hand parsing works fine --
{city=Pune, tempC=29.5, condition=Sunny, humidity=48}
city: Pune, temp: 29.5C, condition: Sunny

-- a NESTED object: the same approach quietly gives the wrong field --
{city=Pune, tempC=22.0, condition=Cloudy}
tempC picked up: 22.0 (which one is that -- current, or forecast?)
A regex has no idea which { } a field belongs to; a real parser does.

The nested input has two tempC fields — one inside "current" (29.5) and one inside "forecast" (22.0) — and the by-hand parser has no concept of "inside," so it just keeps the last one it sees (22.0), silently. A real JSON parser builds a tree first (object → field → nested object → field) and then lets you ask for current.tempC specifically, which is the only way to answer "which one did you mean?" correctly. This is the exact trade-off the README's scope calls out as "parsing JSON by hand vs. with a library": by hand is a reasonable, honest shortcut for a flat payload you control yourself (like the weather lookup in section 9); reach for Jackson or Gson the moment the JSON has any real nesting, or comes from a service you don't control.

Full program: examples/JsonByHandDemo.java.

Done here? The practice set for Part 11 — including the solutions — is on the part page.

Search the guide