Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

How does Gson convert a Java object to JSON and back with new Gson().toJson(obj) and fromJson(json, Order.class)? What does it use to read fields, and how are nulls handled by default?

Gson converts objects by reflection on their declared fields, including private fields and fields inherited from superclasses; it never calls getters or setters. By default it leaves null fields out of the output (GsonBuilder.serializeNulls() includes them), skips transient and static fields, and when reading it ignores unknown JSON properties and leaves fields that are missing from the JSON at their Java default. A Gson instance is thread-safe, so we create it once and reuse it.

Why this question is asked

Gson is a small JSON library from Google that many projects use because it needs almost no setup: one line turns an object into JSON. That simplicity hides several decisions, and they surprise people in production: a field that is null disappears from the payload, a getter with logic is never called, and a missing property silently becomes 0. Interviewers ask this question to check that we know where Gson gets its data from and what its defaults are, because those defaults decide what our API actually sends. In this answer, we will serialize and deserialize an Order step by step, see exactly which members Gson reads, look at its null and missing-value rules, and finish with how to use a Gson instance correctly.

1A Quick Recap of the Two Calls

toJson(obj) walks an object and writes JSON text. fromJson(json, Order.class) does the reverse: it reads JSON text and builds an Order. For every class it meets, Gson needs a type adapter, an object that knows how to write and read that type. It has built-in adapters for strings, numbers, booleans, collections, maps and arrays. For any other class, such as our Order, it builds a reflective adapter on the fly. Reflection means inspecting the class at run time to find its fields and read or set them, even when they are private.

2Serializing an Order

Here is a plain class with a few kinds of fields and a getter that is not backed by a field.

Java
class Base { protected long id; }
class Order extends Base {
private String customer;
private String note; // null in this example
private transient String cacheKey; // marked transient
static int created; // a static field
public String getLabel() { return "Order " + id; } // a getter with no field
}
Gson gson = new Gson();
Order o = new Order(); // id = 7, customer = "Ana", note = null, cacheKey = "k7"
System.out.println(gson.toJson(o));
// {"customer":"Ana","id":7}
What Gson writes for each member of Order
MemberWritten?Why
private String customeryesGson reads all declared fields, any visibility
protected long id (in Base)yessuperclass fields are included
String note = nullnonull fields are omitted unless serializeNulls()
transient String cacheKeynotransient fields are skipped by default
static int creatednostatic fields are skipped by default
getLabel()nogetters are never called
The same rules apply in reverse when reading.

Notice four things in the output. The private field customer is there, because Gson reads fields directly and does not care about visibility. The inherited field id is there too, because Gson walks up the class hierarchy and includes the fields of every superclass. There is no label key, because Gson never calls getters, so computed values are invisible to it. And note, cacheKey and created are all missing, each for a different reason, which the table below sums up.

The fact that Gson reads fields rather than getters is a real difference from Jackson, which by default looks at getters. It means Gson output follows the internal state of the object, so renaming a private field changes the JSON.

3How Nulls Are Handled

Gson's default is to omit a field whose value is null. That keeps payloads small, but it means a client cannot tell "the note is empty" from "this server does not know about notes". When the API contract says nulls must be present, we build the Gson instance with serializeNulls().

Java
Gson withNulls = new GsonBuilder().serializeNulls().create();
System.out.println(withNulls.toJson(o));
// {"customer":"Ana","note":null,"id":7}

The setting also affects null values inside maps, which are dropped by default as well. Whichever choice we make, the important thing is that it is made once, on the shared instance, and matches the documented contract.

4Deserializing, Missing and Unknown Properties

Reading works the other way round. Gson creates an Order instance, then for each property in the JSON looks for a field with the same name and sets it by reflection.

Java
Order a = gson.fromJson("{\"customer\":\"Bo\",\"extra\":true}", Order.class);
System.out.println(a.id); // 0: missing in the JSON, so it keeps the default
System.out.println(a.customer); // Bo
// "extra" has no matching field, so it is ignored without an error

Two rules show here. A property that is missing from the JSON is simply not set, so the field keeps whatever value it had after the object was created: 0, false or null for a plain field. An unknown property, one with no matching field, is skipped silently. That makes Gson tolerant when a server adds new fields, but it also means a typo in a property name produces no error at all, just a missing value.

How the object is created matters too. If the class has a no-arg constructor, Gson calls it, so field initializers run. If not, Gson allocates the object without running any constructor, and initializers are skipped. That is a common source of surprising zeros, and it is worth knowing before the follow-up questions come.

5Creating and Reusing the Gson Instance

Building the reflective adapter for a class takes work: Gson inspects the class and caches the result inside the Gson instance. A Gson object is immutable and thread-safe once created, so the right pattern is a single shared instance, created at startup with the settings we want, and reused everywhere. Calling new Gson() inside every request throws that cache away each time and, worse, invites different parts of the code to use different settings.

Java
public final class Json {
public static final Gson GSON = new GsonBuilder().serializeNulls().create();
private Json() { }
}
String body = Json.GSON.toJson(order); // same settings and cached adapters everywhere

6Follow-up questions

What happens to a field annotated with @SerializedName?

@SerializedName("customer_name") on the field customer makes Gson use customer_name as the JSON key both when writing and when reading, instead of the Java field name. It can also take alternate names, which are accepted only when reading, so @SerializedName(value = "customer_name", alternate = {"name"}) writes customer_name but still reads old payloads that send name. It overrides any field naming policy configured on the builder for that one field.

Can Gson use getters instead of fields?

Not with its default reflective adapter. If a value must come from a getter or must be computed, we write a TypeAdapter or JsonSerializer for that type, or use a DTO whose fields hold exactly what we want to send.

Does Gson keep field order?

It writes fields in the order reflection returns them, which in practice is the declaration order of each class, with the subclass's fields before its superclass's. JSON objects are unordered by definition, so clients should never rely on the order.

7Conclusion

In this answer, we saw that Gson's reflective adapter reads and writes declared fields directly, including private and inherited ones, and never calls getters. By default it omits null fields unless serializeNulls() is set, skips transient and static fields, ignores unknown properties when reading and leaves missing ones at their Java default. Because a Gson instance caches its adapters and is thread-safe, we configure one at startup and share it.

What to say in the interviewAbout 80 seconds aloud

Open with

Gson works on fields, not on getters and setters. When I call toJson, it finds or builds a type adapter for the class, and for my own classes that is a reflective adapter that reads every declared field, private ones included, and walks up to the superclass fields as well.

Then, if they want more

Getters are never called, so a computed getter does not appear in the JSON. By default, a field that is null is left out of the output; if the contract needs explicit nulls, I build the Gson with GsonBuilder.serializeNulls. transient and static fields are skipped.

On fromJson, Gson creates the object, using the no-arg constructor if there is one, and then sets each field that matches a JSON property by name.

A property missing from the JSON leaves the field at its default, for example 0 or null, and an unknown property is ignored without an error, which is tolerant but also hides typos. @SerializedName changes the JSON name for a field, with alternate names accepted only when reading.

Finally, a Gson instance is immutable and thread-safe and caches its adapters, so I create one configured instance and reuse it rather than calling new Gson everywhere.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does Gson convert a Java object to JSON and back with new Gson().toJson(obj) and...": https://scrivio-interview-library.netlify.app/java/json-libraries/eff0168da8/