BackendBench
Coffee

Unravel โ€บ Java concepts โ€บ I/O and files

I/O and data

Gson and other JSON APIs

Gson, org.json and JSON-B are other ways to turn JSON into Java objects and back.

Learn these first

At a glance

Mental model

Different translators for the same language.

What happens, in order
  1. 1gson.toJson(obj) writes JSON; gson.fromJson(json, Order.class) reads itFor generics use new TypeToken<List<Order>>(){}.getType() because the type is erased at run time.
  2. 2@SerializedName("order_id") maps a different JSON name onto a field; @Expose with excludeFieldsWithoutExposeAnnotation() whitelists fields; transient fields are skipped
  3. 3Tree model: JsonParser.parseString(text).getAsJsonObject().get("id").getAsInt() reads without a class; JsonObject and JsonArray can also build JSON by hand
  4. 4org.json offers new JSONObject(text).getString("name"), which throws on missing keys, while optString returns a default
Remember
Watch out
Creating a new Gson for every callParsing generic types without a TypeTokenAssuming missing fields cause an errorReading large numeric ids as doubles
Example (highlighted lines explain it)
import com.google.gson.*;import com.google.gson.reflect.TypeToken;import java.util.List;public class Json {  private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();  static class Order { @com.google.gson.annotations.SerializedName("order_id") long id; String customer; }  static String write(Order o) { return GSON.toJson(o); }  static List<Order> read(String json) { return GSON.fromJson(json, new TypeToken<List<Order>>() {}.getType()); }  static int idOf(String json) { return JsonParser.parseString(json).getAsJsonObject().get("id").getAsInt(); }}
  1. line 2 uses TypeToken, the core of Gson and other JSON APIs
  2. line 5 uses Gson, the core of Gson and other JSON APIs
  3. line 6 uses SerializedName, the core of Gson and other JSON APIs
  4. line 7 uses toJson, the core of Gson and other JSON APIs
  5. line 8 uses fromJson, the core of Gson and other JSON APIs
  6. line 9 uses JsonParser, the core of Gson and other JSON APIs
Read the full explanation (about 1 min)

Gson, org.json and JSON-B are other ways to turn JSON into Java objects and back. Gson (new Gson().fromJson(text, Order.class)) is popular on Android and in small tools; Jackson dominates in Spring.

A mental model

Different translators for the same language. They all convert between JSON text and objects, but each has its own habits about missing fields, naming and dates.

How it works

gson.toJson(obj) writes JSON; gson.fromJson(json, Order.class) reads it. For generics use new TypeToken<List<Order>>(){}.getType() because the type is erased at run time.

@SerializedName("order_id") maps a different JSON name onto a field; @Expose with excludeFieldsWithoutExposeAnnotation() whitelists fields; transient fields are skipped.

Tree model: JsonParser.parseString(text).getAsJsonObject().get("id").getAsInt() reads without a class; JsonObject and JsonArray can also build JSON by hand.

org.json offers new JSONObject(text).getString("name"), which throws on missing keys, while optString returns a default.

Going deeper

Gson uses fields directly through reflection and skips constructors (it uses Unsafe if there is no no-arg constructor), so initialisers and invariants may not run. Missing JSON fields leave the Java default (null, 0) silently.

Numbers parsed into Object or Map become Double, so a 64-bit id loses precision. Declare a real class with a long field.

Build the Gson once and reuse it; it is thread safe. Do not use these libraries to parse untrusted huge input without size limits.

Under the hood

Gson builds a registry of TypeAdapters per type (reflective adapters for classes, built-ins for collections and dates) and caches them in the Gson instance, which is why creating it per call is wasteful.

Common mistakes

  • Creating a new Gson for every call.
  • Parsing generic types without a TypeToken.
  • Assuming missing fields cause an error.
  • Reading large numeric ids as doubles.

How Unravel recognises it

When you paste code, Unravel looks for these signs of gson and other json apis. Spotting them yourself is a good habit when you read unfamiliar code:

Part of a learning path

Related concepts

Frequently asked questions

What is Gson and other JSON APIs?

Gson, org.json and JSON-B are other ways to turn JSON into Java objects and back. Gson (new Gson().fromJson(text, Order.class)) is popular on Android and in small tools; Jackson dominates in Spring.

What are the most common mistakes with Gson and other JSON APIs?

Creating a new Gson for every call. Parsing generic types without a TypeToken. Assuming missing fields cause an error. Reading large numeric ids as doubles.

How can I see Gson and other JSON APIs in real code?

Paste your own Java into Unravel and it will point out where gson and other json apis appears, explain how it works at the detail level you choose, and draw the flow of the code around it.