Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A gateway service must forward JSON payloads while changing only two fields. Would you bind to POJOs, use the tree model, or use streaming? Discuss memory, correctness and schema evolution.

Binding to POJOs is the wrong default for a pass-through gateway, because fields the classes do not know are dropped unless we collect them with @JsonAnySetter, which is easy to get wrong. The tree model keeps every field and its order and is simple to edit, at the cost of memory for large documents, while streaming with JsonParser and JsonGenerator handles any size with little memory but needs harder code. Whatever we choose, we keep numbers exact with BigDecimal for floats; for most payloads under a few megabytes the tree model is the pragmatic choice.

Why this question is asked

A gateway that forwards JSON while changing a couple of fields looks trivial until a downstream team complains that a field they added last week disappears in transit, or that an amount of 0.1 arrived as 0.1000000000000000055. The gateway's job is to change two fields and leave everything else exactly as it was. Interviewers ask this design question to see whether we can match the tool to that job. In this answer, we will set out the requirement, then look at POJO binding, the tree model and streaming in turn, deal with number precision, and finish with a recommendation.

1What the Gateway Must Guarantee

Let us make the task concrete. The gateway receives order documents from partners, replaces the value of customerId with an internal id, sets a field called source, and forwards the result. Documents are usually 5 to 50 KB and at most 5 MB, and partners add their own fields whenever they like.

Three requirements follow. Correctness: every field we do not touch arrives unchanged, including fields we have never seen, nested structures and number values. Memory: the gateway handles hundreds of concurrent requests, so per-request memory must stay bounded. Schema evolution: when partners add fields, the gateway must not need a release.

2Option 1: Binding to POJOs

Binding means reading the JSON into a Java class such as Order and writing the class back. It is the most comfortable code to write, and it is wrong for this job, because the class only has properties for the fields we knew about when we wrote it. With unknown fields ignored, a partner's new field is silently dropped; with unknown fields rejected, the request fails.

Java
public class Order {
public String customerId;
public String source;
public BigDecimal total;
private final Map<String, Object> other = new LinkedHashMap<>();
@JsonAnySetter public void set(String name, Object value) { other.put(name, value); }
@JsonAnyGetter public Map<String, Object> other() { return other; }
}
// in: {"orderId":"o1","customerId":"p-77","total":12.50,"giftWrap":true}
// out: {"customerId":"c-1001","source":"gateway","total":12.50,"orderId":"o1","giftWrap":true}
// every field kept, but the order changed: known properties first, then the rest

@JsonAnySetter collects unknown fields into a map and @JsonAnyGetter writes them back, so data survives. But the order of fields changes, nested unknown objects become maps with the number type surprises of maps, and every developer touching the class must remember the pattern. For pass-through, it fights the tool.

3Option 2: The Tree Model

The tree model reads the whole document into JsonNode objects, keeps every field in its original order, and lets us change just the fields we care about. Writing the tree back produces the same document with our two changes.

Java
ObjectMapper mapper = JsonMapper.builder()
.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) // keep decimals exact
.build();
ObjectNode doc = (ObjectNode) mapper.readTree(body);
doc.put("customerId", idMapping.internalId(doc.path("customerId").asText()));
doc.put("source", "gateway");
String forwarded = mapper.writeValueAsString(doc);
// in: {"orderId":"o1","customerId":"p-77","total":12.50,"giftWrap":true}
// out: {"orderId":"o1","customerId":"c-1001","total":12.50,"giftWrap":true,"source":"gateway"}

The code is short, obviously correct, and unaffected by new partner fields. The price is memory: a tree typically takes several times the size of the JSON text, because every value is an object with its own overhead. For a 50 KB document that is a few hundred kilobytes, which is nothing. For a 5 MB document under concurrency it starts to matter, and for a 500 MB document it is not an option.

4Option 3: Streaming With JsonParser and JsonGenerator

Streaming reads the input token by token with a JsonParser and writes each token straight to a JsonGenerator. We copy everything as it is, except when we see the two field names at the top level, where we write our own value instead. Memory stays at a few kilobytes whatever the document size.

Java
try (JsonParser p = mapper.createParser(in); JsonGenerator g = mapper.createGenerator(out)) {
int depth = 0;
JsonToken t;
while ((t = p.nextToken()) != null) {
if (t == JsonToken.FIELD_NAME && depth == 1 && "customerId".equals(p.currentName())) {
p.nextToken(); // move to the value
g.writeStringField("customerId", idMapping.internalId(p.getText()));
continue;
}
if (t == JsonToken.END_OBJECT && depth == 1) g.writeStringField("source", "gateway");
g.copyCurrentEvent(p); // copy the token unchanged
if (t == JsonToken.START_OBJECT || t == JsonToken.START_ARRAY) depth++;
if (t == JsonToken.END_OBJECT || t == JsonToken.END_ARRAY) depth--;
}
}
// same output as the tree version, with constant memory

Notice how much more code this is for the same result, and how easy it is to get wrong: forget the depth check and a nested customerId gets replaced too; forget that source may already exist and we write a duplicate field. Streaming is the right tool for very large payloads, and the wrong one for ordinary ones. These are Jackson 2 method names; Jackson 3 renamed some generator and parser methods, so check your version.

5Keeping Numbers Exact

By default Jackson reads JSON decimals as double. A double cannot represent most decimal fractions exactly, so a forwarded document can change values: 0.1 stays 0.1 when printed, but a value such as 12.345678901234567890 loses digits, and amounts with trailing zeros such as 12.50 come out as 12.5. Enabling USE_BIG_DECIMAL_FOR_FLOATS makes the tree and binding use BigDecimal and keep the digits. Some versions of Jackson's tree can strip trailing zeros from BigDecimal nodes depending on node factory settings, so check that 12.50 stays 12.50 in a test with your version. Streaming with copyCurrentEvent copies the number text as it was read, which is one of its quiet advantages. Large integers are safe in all three, because Jackson switches to BigInteger when a value does not fit in a long.

Three ways to build the gateway
ApproachUnknown fieldsMemoryCode effort
POJO bindingLost unless @JsonAnySetterLow to mediumLow, but fights pass-through
Tree modelKept, order preservedSeveral times the document sizeLow
StreamingKept, order preservedConstant, a few KBHigh, easy to get wrong
For documents up to a few MB the tree model gives correctness with the least code.

6The Recommendation

For this gateway, with documents of a few kilobytes and at most a few megabytes, I would use the tree model with USE_BIG_DECIMAL_FOR_FLOATS, a request size limit at the edge, and StreamReadConstraints to keep hostile input bounded. It keeps every field, survives schema evolution without releases, and the code is easy to review. I would add a test that forwards a document with unknown nested fields, a decimal with trailing zeros and a very large integer, and asserts that the output equals the input apart from our two fields. If the gateway later has to handle documents of hundreds of megabytes, I would switch that route to streaming and keep the same test.

7Follow-up questions

Why not use a JSON Patch or a string replace instead?

A string replace on JSON text is fragile: it can match inside other values, break escaping, or miss formatting variants. JSON Patch, RFC 6902, describes changes as operations and Jackson-based libraries can apply it to a tree, which is a reasonable way to make the gateway's changes configurable, but underneath it still uses the tree model.

Does the tree model preserve field order?

Yes. ObjectNode keeps fields in insertion order, which for a parsed document is the original order, and put() on an existing field replaces the value in place. New fields are added at the end.

What about duplicate field names in the input?

By default Jackson's tree keeps the last value for a duplicate name, so the output silently has one field. If duplicates must be rejected, STRICT_DUPLICATE_DETECTION on the parser makes Jackson fail on them, which is a good idea at a security boundary.

8Conclusion

In this answer, we saw that POJO binding drops unknown fields unless we use @JsonAnySetter and that it changes order, that the tree model keeps all fields and their order with simple code at the cost of memory, and that streaming with JsonParser and JsonGenerator uses constant memory but needs careful code. We kept numbers exact with BigDecimal for floats and chose the tree model for payloads under a few megabytes.

What to say in the interviewAbout 80 seconds aloud

Open with

For a gateway the key requirement is that everything I do not touch arrives unchanged, including fields I have never seen. That rules out plain POJO binding, because unknown fields are dropped; with JsonAnySetter and JsonAnyGetter I can keep them, but the field order changes and nested values become maps, so I would be fighting the tool.

Then, if they want more

The tree model fits the job: readTree, cast to ObjectNode, put the two new values, write it back. It keeps every field in its original order, needs no release when partners add fields, and the code is easy to review. Its cost is memory, several times the document size, which is fine for kilobytes and a few megabytes.

Streaming with JsonParser and JsonGenerator, copying each token and replacing only the two top-level fields, keeps memory constant for any size, but it is much more code and easy to get wrong, for example replacing a nested field with the same name.

I would also enable USE_BIG_DECIMAL_FOR_FLOATS so decimals stay exact, and test that trailing zeros survive with my Jackson version. So for typical payloads I choose the tree model, with size limits at the edge, and switch a route to streaming only if it must handle very large documents.

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 documentation below. 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 "A gateway service must forward JSON payloads while changing only two fields. Would you...": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/f6fc95d44c/