Master JSON Control in Spring Boot 3: Practical Guide to @JsonProperty, @JsonView & Mix‑ins
This article explains how to fine‑tune JSON responses in Spring Boot 3 using Jackson annotations such as @JsonProperty, @JsonFormat, @JsonView, and Mix‑ins, covering field hiding, renaming, null handling, date/number formatting, view‑based serialization, and custom ObjectMapper configuration with code examples.
1. Introduction
In Spring Boot development, the design of REST API JSON responses directly impacts client experience and data security. By default, Jackson serializes fields based on public getter methods, but many scenarios require finer control such as hiding sensitive fields, renaming fields, forcing null output, or formatting dates and numbers. This article introduces how to use @JsonProperty, @JsonFormat, @JsonView, and Mix‑ins to customize JSON output without modifying original classes.
2. Practical Cases
2.1 Controlling JSON Field Output
Jackson determines the JSON content from class fields and methods, selecting public getters by default. Fields without getters are ignored unless explicitly configured.
public class Customer {
private String name;
private String email;
private Integer age;
public String getName() { return name; }
public String getEmail() { return email; }
public Integer getAge() { return age; }
}Serializing an instance of this class yields:
{
"name": "Spring Boot3实战案例200讲",
"email": "[email protected]",
"age": 33
}If a field such as private String address; has no getter, it will not appear in the JSON output.
2.2 Renaming Fields
To expose a field under a different name without changing the source code, use @JsonProperty.
public class Customer {
// ...
@JsonProperty("address")
private String homeAddress;
}2.3 Outputting Null Fields
Annotate a field with @JsonInclude(JsonInclude.Include.ALWAYS) or configure the ObjectMapper to always include null values.
@JsonInclude(JsonInclude.Include.ALWAYS)
public class Customer { }
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);Spring Boot can also be configured via properties:
spring:
jackson:
default-property-inclusion: always2.4 Formatting Dates and Numbers
Use @JsonFormat to specify date patterns or to serialize numbers as strings.
public class User {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
}Resulting JSON: {\n "createTime": "2025-08-10 07:30:30"\n} For numeric fields, applying @JsonFormat(shape = JsonFormat.Shape.STRING) forces string output, avoiding rounding issues in JavaScript.
@JsonFormat(shape = JsonFormat.Shape.STRING)
private BigDecimal price;2.5 Controlling Fields with @JsonView
Define view interfaces to expose different subsets of fields for public and internal APIs.
public class User {
@JsonView(Public.class)
private Long id;
@JsonView(Public.class)
private String username;
@JsonView(Internal.class)
private String password;
public interface Public {}
public interface Internal extends Public {}
}Apply the view in a controller method:
@GetMapping("/{id}")
@JsonView(User.Public.class)
public User queryUser(@PathVariable Long id) {
return new User(666L, "Pack_xg", "123123");
}2.6 Using Mix‑ins
When you cannot modify a third‑party class, create a Mix‑in to add annotations externally.
public abstract class UserMixIn {
@JsonIgnoreProperties(value = {"password"})
// rename field
@JsonProperty("emailAddress")
abstract String getEmail();
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM", timezone = "GMT+8")
abstract Date getBirth();
}Register the Mix‑in with a customizer:
@Component
public class PackJackson2ObjectMapperBuilderCustomizer implements Jackson2ObjectMapperBuilderCustomizer {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.mixIn(User.class, UserMixIn.class);
}
}2.7 Controller Example
@GetMapping("/query")
public ResponseEntity<?> query() {
return ResponseEntity.ok(new User("pack", "123123", new Date(), "[email protected]"));
}2.8 Result
The endpoint returns JSON according to the configured Mix‑in and view settings.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
