JSON and XML boundaries
What you will learn
JSON and XML represent structured data, not just delimited text. Parse with a format-aware library, enforce size and structure limits, then validate the resulting values. Java SE includes XML APIs but does not include a general JSON parser; use an approved external library for JSON.
- Separate syntax parsing from schema and domain validation.
- Configure a bounded local XML parser to reject DTDs and external access.
- Explain how external JSON libraries handle escaping and validation.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies.
Parse a small XML document safely
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { static Document parse(String xml) throws Exception { if (xml.length() > 4096) throw new IllegalArgumentException("document too long"); var f = DocumentBuilderFactory.newDefaultInstance(); f.setNamespaceAware(true); f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); f.setXIncludeAware(false); f.setExpandEntityReferences(false); var b = f.newDocumentBuilder(); b.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } }); return b.parse(new InputSource(new StringReader(xml))); } public static void main(String[] args) throws Exception { var doc = parse("<item code=\"AB12\"><name>Tea & Cake</name><qty>7</qty></item>"); var item = doc.getDocumentElement(); System.out.println(item.getTagName()); System.out.println(item.getAttribute("code")); System.out.println(item.getElementsByTagName("name").item(0).getTextContent()); }}Expected output:
itemAB12Tea & CakeThe parser converts an XML entity reference into text; parsing alone does not check quantity or schema.
Parsing is only the first gate
A well-formed document can still violate a business contract. For this inventory example require one item element, a code matching two ASCII letters plus digits, and a quantity between 0 and 999. Check element/attribute names, cardinality, value types, unknown fields and null or missing values according to the agreed schema. Do not accept arbitrary object types or Java native serialized objects. Use a byte cap before reading network input and configure parser depth and token limits; a String length cap is only a second boundary after decoding.
XML: deny external resolution
The examples use the JDK built-in DOM provider with secure processing enabled, DTD declarations rejected, external DTD and schema access denied, XInclude disabled and an explicit throwing error handler. If a security feature cannot be configured, fail closed; do not silently continue. These are bounded in-memory examples, not a universal XML gateway. Entity references such as & in normal XML are still supported. For output, use DOM text nodes or a trusted XML writer; never concatenate unescaped values into markup.
JSON: external dependency and explicit contract
Use a reviewed, pinned release of Jackson or JSON-B through approved build tooling (later chapter). Jackson 2.x and 3.x have different package names and configuration APIs. The following illustrative Jackson 2.x snippet is NOT RUN because no approved dependency is available. It assumes a bounded UTF-8 document, uses a tree to reject unexpected shape and checks types before extracting values. Configure stream constraints for depth/string/number lengths appropriate to the schema, reject duplicates and trailing tokens, avoid default polymorphic typing, and serialize with a library. A parser accepting a document does not guarantee valid business data.
// External Jackson 2.x dependency required; not compiled in this batch.// Imports: com.fasterxml.jackson.databind.*// Inside a method declaring the relevant checked parsing exception:ObjectMapper mapper = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY) .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);JsonNode item = mapper.readTree("{\"qty\":7}");if (item == null || !item.isObject() || item.size() != 1 || !item.path("qty").isIntegralNumber() || !item.path("qty").canConvertToInt() || item.path("qty").intValue() < 0 || item.path("qty").intValue() > 999) { throw new IllegalArgumentException("invalid item");}String json = mapper.writeValueAsString(item);The intended serialized JSON is {"qty":7} (whitespace and field ordering are not a general contract). Dependency resolution and execution are deferred.
Reject a DTD without external I/O
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { static Document parse(String xml) throws Exception { if (xml.length() > 4096) throw new IllegalArgumentException("document too long"); var f = DocumentBuilderFactory.newDefaultInstance(); f.setNamespaceAware(true); f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); f.setXIncludeAware(false); f.setExpandEntityReferences(false); var b = f.newDocumentBuilder(); b.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } }); return b.parse(new InputSource(new StringReader(xml))); } public static void main(String[] args) throws Exception { try { parse("<!DOCTYPE item><item/>"); throw new AssertionError("DTD accepted"); } catch (SAXParseException e) { System.out.println("DTD rejected"); } }}Expected output:
DTD rejectedEven an empty DTD is rejected, with no external file or network address in the fixture.
Validate a narrow XML contract
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { static Document parse(String xml) throws Exception { if (xml.length() > 4096) throw new IllegalArgumentException("document too long"); var f = DocumentBuilderFactory.newDefaultInstance(); f.setNamespaceAware(true); f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); f.setXIncludeAware(false); f.setExpandEntityReferences(false); var b = f.newDocumentBuilder(); b.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } }); return b.parse(new InputSource(new StringReader(xml))); } public static void main(String[] args) throws Exception { for (String xml : List.of("<item code=\"AB12\">7</item>", "<item code=\"AB12\">-1</item>", "<item code=\"AB12\"><qty>7</qty></item>")) { var e = parse(xml).getDocumentElement(); boolean valid = "item".equals(e.getTagName()) && e.getNamespaceURI() == null && e.getAttributes().getLength() == 1 && e.getAttribute("code").matches("[A-Z]{2}[0-9]{1,4}") && e.getChildNodes().getLength() == 1 && e.getFirstChild().getNodeType() == Node.TEXT_NODE && e.getTextContent().matches("[0-9]{1,3}"); System.out.println(valid); } }}Expected output:
truefalsefalseThis deliberately narrow schema requires exactly one text child, one code attribute, no namespace, and a nonnegative bounded decimal quantity. It is not a general XML Schema validator.
Create escaped XML text using DOM
import java.util.*;import java.util.regex.*;import java.nio.*;import java.nio.charset.*;import java.io.*;import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.xml.sax.*;import org.xml.sax.helpers.DefaultHandler;import org.w3c.dom.*;public class Main { static Document parse(String xml) throws Exception { if (xml.length() > 4096) throw new IllegalArgumentException("document too long"); var f = DocumentBuilderFactory.newDefaultInstance(); f.setNamespaceAware(true); f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); f.setXIncludeAware(false); f.setExpandEntityReferences(false); var b = f.newDocumentBuilder(); b.setErrorHandler(new DefaultHandler() { @Override public void error(SAXParseException e) throws SAXException { throw e; } @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } }); return b.parse(new InputSource(new StringReader(xml))); } public static void main(String[] args) throws Exception { var doc = parse("<item/>"); var e = doc.getDocumentElement(); e.setTextContent("Tea & <Cake>"); System.out.println(e.getTextContent()); var f = javax.xml.transform.TransformerFactory.newDefaultInstance(); f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); f.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); var t = f.newTransformer(); t.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes"); var out = new StringWriter(); t.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); System.out.println(parse(out.toString()).getDocumentElement().getTextContent().equals(e.getTextContent())); }}Expected output:
Tea & <Cake>trueThe identity transformer handles XML escaping. The round-trip assertion checks logical text, not provider-specific serialization formatting.
Common mistakes
Do not parse JSON with regex or hand-build XML using string concatenation. Do not suppress parser configuration errors. Never allow arbitrary external entities or untrusted native Java deserialization. Reject unexpected types and shapes rather than relying on coercion.
Practice
Parse the fixed XML <item code="CD9">12</item> using the bounded secure helper. Validate the same narrow structure as the third example and print CD9:12 only if valid.
Expected output:
CD9:12Compare your answer with the manual practice criteria.
Official reading: XML security · Jackson · Jackson features. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JSON and XML boundaries — knowledge check
Original regex, text and structured data questions. Java 21-compatible scope.
Does Java SE supply a general JSON parser?
What should happen if required XML security configuration fails?
Does well-formed XML imply valid business data?
Which is appropriate for XML output?
What is needed before parsing incoming bytes?