Returning Simple Strings as JSON Responses in Spring MVC Rest Controllers

Nov 13, 2025 · Programming · 12 views · 7.8

Keywords: Spring MVC | JSON Response | REST Controller | String Serialization | Message Conversion

Abstract: This technical article provides an in-depth exploration of methods for returning simple strings as JSON-formatted responses in Spring MVC framework. Through analysis of Spring's automatic serialization mechanism, @RestController annotation functionality, and produces attribute configuration, it details two main solutions: using wrapper objects for structured JSON returns and manually constructing JSON strings. The article combines code examples with principle analysis to help developers understand Spring's response processing flow and offers best practice recommendations for real-world applications.

JSON Response Processing Mechanism in Spring MVC Framework

When building RESTful APIs with Spring MVC, returning JSON-formatted responses is a common requirement. The Spring framework, through its powerful message conversion mechanism, can automatically serialize Java objects into JSON format. However, developers may encounter confusion when needing to return simple strings.

Problem Context and Core Challenges

Consider the following typical controller code:

@RestController
public class TestController {
    @RequestMapping("/getString")
    public String getString() {
        return "Hello World";
    }
}

In this example, Spring by default writes the string directly to the HTTP response body, rather than wrapping it as valid JSON format. This may not be ideal for certain client libraries (such as RestyGWT) that expect to receive standard JSON responses.

Solution One: Using Wrapper Objects

The most elegant solution involves creating a dedicated response wrapper class:

public class StringResponse {
    private String response;
    
    public StringResponse(String response) {
        this.response = response;
    }
    
    public String getResponse() {
        return response;
    }
    
    public void setResponse(String response) {
        this.response = response;
    }
}

Then use this wrapper class in the controller:

@RestController
public class TestController {
    @RequestMapping(value = "/getString", 
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_VALUE)
    public StringResponse getString() {
        return new StringResponse("Hello World");
    }
}

The advantages of this approach include:

Solution Two: Manual JSON String Construction

For simple scenarios, JSON strings can be manually constructed:

@RestController
public class TestController {
    @RequestMapping(value = "/getString", 
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_VALUE)
    public String getString() {
        return "{\"response\": \"Hello World\"}";
    }
}

While straightforward, this method has several drawbacks:

Deep Analysis of Spring's Message Conversion Mechanism

Spring MVC handles HTTP request and response message conversion through the HttpMessageConverter interface. When using the @RestController annotation, Spring automatically configures MappingJackson2HttpMessageConverter to handle JSON serialization.

Key configuration points:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter());
    }
}

Important Role of the Produces Attribute

The configuration produces = MediaType.APPLICATION_JSON_VALUE informs Spring that:

Best Practices in Practical Applications

In real project development, it is recommended to:

  1. Create unified response wrapper classes for all API responses
  2. Include status code, message, and data fields
  3. Use enums to define common response statuses
  4. Implement unified exception handling mechanisms

Example unified response class:

public class ApiResponse<T> {
    private int code;
    private String message;
    private T data;
    
    // Constructors, getters, setters omitted
}

Performance Considerations and Optimization Suggestions

When handling large volumes of simple string responses, consider:

Conclusion

For returning simple strings as JSON responses in Spring MVC, the wrapper object approach is recommended. This method not only generates standard JSON format but also provides better type safety and extensibility. By deeply understanding Spring's message conversion mechanism and properly configuring the produces attribute, developers can build more robust and maintainable RESTful APIs.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.