Master Spring Boot Web Development: Build Your First API and Customize JSON

This tutorial walks you through creating a Spring Boot web project, adding the starter dependency, implementing a REST endpoint, customizing Tomcat port and context path, and configuring Jackson for JSON output such as date formatting and global ObjectMapper settings.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Master Spring Boot Web Development: Build Your First API and Customize JSON

Introduction

This is the fifth article in a Spring Boot series and introduces the essential features for web development with Spring Boot.

Spring Boot Version

The examples are based on Spring Boot 2.3.4.RELEASE.

Prerequisites

Spring Boot’s web starter provides its own auto‑configuration; you should avoid adding @EnableWebMvc to any configuration class.

Adding Dependency

Include the web starter in pom.xml:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

First API Development

Create a controller that returns a user object based on the path variable id:

@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/{id}")
    public Object getById(@PathVariable("id") String id) {
        return User.builder()
            .id(id)
            .name("不才陈某")
            .age(18)
            .birthday(new Date())
            .build();
    }
}

Run the application and request http://localhost:8080/user/1 to receive:

{
  "id": 1,
  "age": 18,
  "birthday": 1601454650860,
  "name": "不才陈某"
}

Customizing Tomcat Port

Change the default port by adding the following line to application.properties:

server.port=9090

Customizing Context Path

Set a custom project context path: server.servlet.context-path=/springboot01 After these changes, the endpoint is accessed at http://localhost:9090/springboot01/user/1.

JSON Formatting

Spring Boot uses Jackson for JSON serialization. You can adjust global settings in application.properties or override them per field with annotations.

Date Format

Configure a human‑readable date format globally:

spring.jackson.date-format= yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone= GMT+8

Or apply @JsonFormat on a field for local configuration:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm", timezone = "GMT+8")
private Date birthday;

After configuration, the JSON response shows the date as 2020-09-30 17:21.

Other Jackson Properties

All Jackson options are prefixed with spring.jackson and can be set in the properties file.

Configuring via Java Class

Define a @Configuration class that provides a custom ObjectMapper bean, which overrides the default JacksonAutoConfiguration:

/**
 * Custom Jackson serialization and deserialization rules (global configuration)
 */
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        builder.locale(Locale.CHINA);
        builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
        builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        builder.modules(new CustomTimeModule());
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.registerModule(new CustomTimeModule());
        return objectMapper;
    }
}

Conclusion

The article demonstrated how to set up a Spring Boot web project, create a simple REST API, customize the embedded Tomcat port and context path, and fine‑tune JSON output using both global properties and a custom ObjectMapper configuration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ConfigurationJSONSpring BootWeb DevelopmentREST APIJackson
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.