Skip to content

JsonApprovals.verifyJson() silently strips null values from JSON #767

@LarsEckart

Description

@LarsEckart

Bug

JsonApprovals.verifyJson(json) silently removes null values from the input JSON during pretty-printing.

Steps to reproduce

Gson gson = new GsonBuilder().serializeNulls().create();
Person person = new Person("Max", null, 1);
String json = gson.toJson(person);
// json = {"firstName":"Max","lastName":null,"age":1}

// This preserves nulls:
Approvals.verify(json);

// This strips nulls:
JsonApprovals.verifyJson(json);

Expected: verifyJson output contains "lastName": null
Actual: "lastName" is silently dropped from the output

Root cause

JsonUtils.prettyPrint() creates a new GsonBuilder without .serializeNulls(). Gson's JsonWriter.nullValue() silently skips null property values when serializeNulls is false (default). So when the JSON is parsed into a JsonElement tree and re-serialized, explicit JsonNull entries are dropped.

The same issue exists in the reorderFields code path.

Suggested fix

Add .serializeNulls() to the GsonBuilder in JsonUtils.prettyPrint() (and asJson() for reorderFields). These are formatting functions — they should preserve content faithfully.

Workaround

Pass a custom GsonBuilder to enable serializeNulls:

JsonApprovals.verifyJson(json, false, GsonBuilder::serializeNulls);

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions