Parse JSON into Java objects

How JSON-to-Java parsing works with Jackson, Gson and org.json: what changes, what can be lost on a round trip, and when to keep the raw string instead.

Turning JSON text into Java objects looks like a simple formatting step, but it is a real transformation. The text is read, checked against JSON syntax and converted into Java values. Some details of the original text are kept, some are normalized, and a few can be lost. This review explains what the conversion changes, which approach fits which job, and when you are better off leaving the JSON as a plain string.

Is parsing JSON into Java objects the right move?

For most application code, binding JSON to typed Java classes or records is the right choice. The main benefit is that the compiler and your IDE see named fields with real types instead of string keys, so mistakes surface early and the rest of the code reads clearly. The tradeoff is that binding enforces your model on the data. Anything the model does not describe, such as unknown fields, original formatting, key order or numbers too large for the target type, is either dropped, rejected or changed. If you control the data shape and only need its meaning, bind it. If you need the exact original text, or the shape is unknown, choose a different approach.

Keeping the JSON as a plain string, or parsing only into a generic tree, is preferable when:

  • You only pass the payload through, store it or log it, and never read individual fields.
  • The exact bytes matter, for example when the text is signed, hashed or compared against a stored copy.
  • The structure varies between messages or is not documented, so a fixed class would break or silently drop data.
  • You need only one or two values from a large document, where a tree lookup or streaming read is simpler than modeling everything.

What the conversion actually changes

JSON is text. A Java String containing JSON is still only characters, so the common question of how to convert a string to JSON in Java really means parsing that string into a structure a program can query. A parser reads the characters, resolves escape sequences, checks the syntax and produces values: objects, arrays, strings, numbers, booleans and null. What you get back depends on which of three approaches you choose.

Approach | What you get | Good fit | Main tradeoff
Typed binding (Jackson readValue, Gson fromJson, Jakarta JSON Binding) | Instances of your own classes or records | Known, stable data shapes in application code | Data outside the model is ignored or rejected; you maintain the classes
Tree model (Jackson JsonNode, Gson JsonElement, org.json JSONObject, Jakarta JSON Processing JsonObject) | A generic map-like structure navigated by key and index | Unknown or variable shapes, quick inspection, partial reads | No compile-time checking; key typos fail at runtime or return empty values
Streaming (Jackson JsonParser, Gson JsonReader) | A sequence of tokens you handle one by one | Very large inputs or reading a few fields efficiently | More code, and you manage the structure yourself

Pretty-printing or minifying JSON is a different kind of change. It alters only whitespace, which is presentation. Parsing changes how the data is stored: once the text becomes Java objects, the original indentation, spacing and escape choices no longer exist anywhere in memory.

Typed binding with Jackson

public record Person(String name, int age) {}

ObjectMapper mapper = new ObjectMapper();
Person p = mapper.readValue(json, Person.class);

// Generic types need a type token because of erasure
List<Person> people = mapper.readValue(
        jsonArray, new TypeReference<List<Person>>() {});

Jackson's readValue throws a checked exception when the input is malformed or does not fit the target type. By default it also fails on properties the class does not declare. That strictness catches mistakes, but it breaks when a producer adds a new field, so many projects relax it on purpose. Record support depends on the library version, so check the documentation for the version you use.

Typed binding with Gson

Gson gson = new Gson();
Person p = gson.fromJson(json, Person.class);

Type listType = new TypeToken<List<Person>>() {}.getType();
List<Person> people = gson.fromJson(jsonArray, listType);

Gson takes the opposite default: it ignores unknown fields, and fields missing from the JSON stay at Java defaults such as null, 0 or false. That tolerance is convenient, but it can hide a renamed or misspelled field. If a class has no no-argument constructor, Gson may create the object without running field initializers, so defaults you assigned in code may not apply.

Parsing a string into a JSON tree

// Jackson tree model
JsonNode root = mapper.readTree(json);
String name = root.path("name").asText();

// org.json
JSONObject obj = new JSONObject(json);
int age = obj.optInt("age", -1);

This is the most direct answer to turning a string into a JSON object in Java when you don't want to define classes. Lookups by key are flexible, but nothing checks the key names until the code runs.

What may not survive a round trip

Parsing to objects and serializing back to JSON keeps the meaning in the common cases. It does not reproduce the original text, and a few edge cases can change the meaning too:

  • Formatting: whitespace, indentation and line breaks are discarded. Output follows the serializer's settings, not the input.
  • Key order: when you bind to a class, output order follows the class or serializer configuration. Hash-based maps do not guarantee any order.
  • Duplicate keys: the JSON specification says object names should be unique but does not define what happens when they are not. Libraries differ: some keep the last value, others reject the document.
  • Number precision: integers too large for int or long either fail or overflow, depending on the library. Values parsed into an untyped Object or Map may become double and lose digits. Use long, BigInteger or BigDecimal where precision matters.
  • Unknown fields: with typed binding, fields not in your class are either rejected or silently dropped. Silently dropped fields are missing when you write the object back out.
  • Null versus missing: a field explicitly set to null and a field that was absent often end up as the same Java null, and the serializer then decides whether to write it.
  • Dates and times: JSON has no date type, so dates arrive as strings or numbers. Mapping them to java.time types needs explicit configuration, such as an extra Jackson module in 2.x versions or a custom adapter in Gson, plus an agreed format and time zone.

Unicode text is preserved in meaning but not necessarily in spelling. An escape such as \u00e9 becomes the character é in the Java String. A serializer may write it back as the raw character or as an escape, and both are equivalent JSON. Characters outside the Basic Multilingual Plane, including most emoji, are stored in Java as two UTF-16 code units, so String.length() counts them as two. Code that truncates or reverses strings by char index can split such characters, or separate a base letter from its combining mark. That is a problem in your own string handling, not in the parser, but it often shows up right after parsing. If the exact original characters or bytes must be kept, store the raw input alongside the parsed object.

Why copied or shared JSON fails to parse

Strict parsers reject a lot of text that merely looks like JSON. This happens often with snippets copied from chat apps, word processors, documentation pages or JavaScript source. Common causes:

  • Curly "smart" quotes substituted for straight double quotes by an editor or messaging app.
  • Single-quoted strings or unquoted keys, which JavaScript object literals allow but JSON does not.
  • Comments and trailing commas, which are not part of standard JSON.
  • A byte order mark or invisible characters, such as non-breaking spaces, at the start of the text or between tokens.
  • Values like NaN or Infinity, which have no JSON representation.

Both Jackson and Gson offer lenient or feature-flag modes that accept some of these forms. Enabling them makes copied input parse, but it widens what your application accepts, and other systems that read the same data may stay strict. For anything shared between systems, fix the input so it is valid JSON rather than loosening the parser.

For human readability, remember that calling toString() on a bound Java object does not produce JSON unless the class was written to do so. To share a readable copy, serialize it through the library with pretty-printing enabled, for example Jackson's writerWithDefaultPrettyPrinter() or Gson's setPrettyPrinting(). That changes presentation only, not content.

Handling untrusted input

When JSON comes from outside your system, bind it to concrete, narrow types. Avoid library features that let the input choose which Java class gets instantiated, such as broad polymorphic or default typing. Those features have been the source of serious deserialization vulnerabilities. Validate values after parsing, because syntactically valid JSON can still contain out-of-range numbers, unexpected nulls or oversized strings.

Gaps in this review

This overview relies on the JSON format rules and widely documented library behavior. It includes no benchmarks, version-specific tests or measured comparisons between libraries. Defaults such as handling of unknown properties, duplicate keys, number types and date support have changed across releases. Check them against the documentation and a small test for the exact library version in your project before relying on them.