JSON & XML

By the end of this lesson you'll be able to turn Java objects into JSON and back with Jackson, walk dynamic JSON with the tree model, and safely read XML — the two data formats that power nearly every API and config file you'll ever touch.

Learn JSON & XML in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.

Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

You should be comfortable with REST APIs (JSON is the standard API format) and Annotations (Jackson uses @JsonProperty , @JsonIgnore , and friends). A basic grasp of maps and lists helps too.

JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are both ways to write data as plain text so two programs can exchange it. Your Java program can't send a live object across the internet, so it serializes the object to text, sends the text, and the other side deserializes it back into an object.

💡 Analogy: Think of flat-pack furniture. The object in memory is the assembled chair. To ship it, you flatten it into a labelled box (serialize to JSON/XML). At the other end someone reads the labels and rebuilds the chair (deserialize). JSON is the lean, modern box; XML is the older box with more packaging and stricter labels.

Here's the same data in both formats so you can feel the difference:

For a brand-new project JSON wins almost every time. XML still shows up in SOAP web services, Maven pom.xml files, and older enterprise systems — so it's worth knowing both.

Jackson is the most popular JSON library for Java, and Spring Boot uses it automatically. The one class you need is ObjectMapper . It does two jobs: writeValueAsString(obj) turns an object into JSON text, and readValue(json, Type.class) turns JSON text back into an object.

You map JSON onto a POJO — a plain class with fields. Two annotations control the mapping: @JsonProperty("key") renames a field in the JSON (handy when the API uses snake_case but you want camelCase in Java), and @JsonIgnore keeps a field out of the JSON entirely (perfect for passwords).

Read every comment in this worked example, then run it:

Fill in the three blanks ( ___ ): the annotation that renames inStock , the serialize method, and the deserialize method. The expected output is in the comments so you can self-check.

Sometimes you only need one or two values from a big response, and writing matching classes would be overkill. Use the tree model : mapper.readTree(json) parses the JSON into a JsonNode you can walk like a document.

mapper.readValue(json, Order.class) — POJO mapping (typed, compile-time safe)

mapper.readTree(json) — tree model (dynamic, no class needed)

node.get("field") — step into an object or array

node.asText() / asInt() / asDouble() — read a leaf value

A JsonNode that holds an array is iterable, so you can loop over it with a normal for loop.

No POJO this time. Fill in the three blanks to parse the JSON, read the top-level city as text, and reach into the nested weather.temp as an int.

Gson is Google's JSON library and the main alternative to Jackson. The API is even smaller — no ObjectMapper to configure, just a Gson object:

Gson is great for small apps or quick scripts where you want zero setup. For anything bigger — especially Spring Boot, which wires up Jackson for you — prefer Jackson for its richer annotations, streaming parser, and ecosystem. Pick one per project and stay consistent.

Java ships with several XML tools. The three you'll meet most:

Support is faded now: the starter only has a comment outline. Parse the scores array with the tree model, sum and count the values, and print the average to one decimal place.

You can now move data in and out of Java with confidence: serialize and deserialize POJOs with Jackson's ObjectMapper , rename and hide fields with @JsonProperty / @JsonIgnore , walk dynamic JSON with the tree model, choose Gson when you want something lighter, and read XML safely while knowing DOM from SAX from JAXB.

Next up: Unit Testing — write reliable tests with JUnit 5 and Mockito.

Practice quiz

Which Jackson method turns a Java object into JSON text?

  • readValue
  • readTree
  • writeValueAsString
  • toJson

Answer: writeValueAsString. mapper.writeValueAsString(obj) serializes an object to JSON; readValue deserializes JSON back to an object.

What does @JsonIgnore do to a field?

  • Keeps it out of the JSON entirely
  • Renames it in the JSON
  • Marks it required
  • Makes it read-only

Answer: Keeps it out of the JSON entirely. @JsonIgnore excludes a field from the JSON — perfect for secrets like passwords.

What is the purpose of @JsonProperty("is_active")?

  • Hides the field
  • Validates the value
  • Marks it as a constructor argument
  • Renames the JSON key while the Java field stays camelCase

Answer: Renames the JSON key while the Java field stays camelCase. @JsonProperty bridges snake_case JSON keys and camelCase Java fields by renaming the key.

When is the tree model (readTree returning a JsonNode) most useful?

  • When you need compile-time type safety
  • When you only need a few values and don't want to write matching POJOs
  • When serializing objects
  • Only for XML

Answer: When you only need a few values and don't want to write matching POJOs. The tree model navigates dynamic JSON without POJOs — ideal when you just need a couple of fields.

Why does Jackson throw 'no default constructor' when deserializing?

  • Jackson needs a no-arg constructor to create the object before setting fields
  • The JSON is invalid
  • The class is final
  • The field is private

Answer: Jackson needs a no-arg constructor to create the object before setting fields. Jackson instantiates with a no-arg constructor first; add one, or use @JsonCreator with @JsonProperty parameters.

What is the key difference between DOM and SAX for XML?

  • DOM is faster always
  • SAX can edit, DOM cannot
  • DOM loads the whole document into memory; SAX streams it with constant memory
  • They are identical

Answer: DOM loads the whole document into memory; SAX streams it with constant memory. DOM builds an in-memory tree (easy to navigate, heavy); SAX/StAX stream forward-only with constant memory.

What is an XXE attack?

  • A JSON parsing error
  • Malicious XML declaring an external entity to read local files or hit internal URLs
  • A SQL injection variant
  • A buffer overflow in Jackson

Answer: Malicious XML declaring an external entity to read local files or hit internal URLs. XXE abuses external entities in XML; prevent it by disabling DOCTYPE/external entities before parsing untrusted XML.

How do you stop Jackson crashing when JSON has fields your POJO doesn't declare?

  • Delete the extra fields
  • Use Gson instead
  • Make all fields public
  • Set FAIL_ON_UNKNOWN_PROPERTIES to false or use @JsonIgnoreProperties(ignoreUnknown = true)

Answer: Set FAIL_ON_UNKNOWN_PROPERTIES to false or use @JsonIgnoreProperties(ignoreUnknown = true). Disabling FAIL_ON_UNKNOWN_PROPERTIES (or the annotation) makes deserialization resilient to extra keys.

Which library is Spring Boot's default for JSON?

  • Gson
  • Jackson
  • org.json
  • JAXB

Answer: Jackson. Spring Boot auto-configures Jackson; Gson is a lighter alternative you can choose for small apps.

JAXB is the XML equivalent of which JSON tool?

  • The DOM parser
  • SAX streaming
  • Jackson's POJO mapping (object to/from markup)
  • A connection pool

Answer: Jackson's POJO mapping (object to/from markup). JAXB maps XML to/from Java objects with annotations — a Marshaller writes objects and an Unmarshaller reads them.