As you are using Spring Boot web, Jackson dependency is implicit and we do not have to define explicitly. You can check for Jackson dependency in your pom.xml in the dependency hierarchy tab if using eclipse.

And as you have annotated with @RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using @ResponseBody when used with @Controller. Rather than placing @ResponseBody on every controller method we place @RestController instead of vanilla @Controller and @ResponseBody by default is applied on all resources in that controller.
Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.
Refer this link: https://stackoverflow.com/a/35822500/5039001

If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.

Answer from prem kumar on Stack Overflow
Top answer
1 of 10
181

As you are using Spring Boot web, Jackson dependency is implicit and we do not have to define explicitly. You can check for Jackson dependency in your pom.xml in the dependency hierarchy tab if using eclipse.

And as you have annotated with @RestController there is no need to do explicit json conversion. Just return a POJO and jackson serializer will take care of converting to json. It is equivalent to using @ResponseBody when used with @Controller. Rather than placing @ResponseBody on every controller method we place @RestController instead of vanilla @Controller and @ResponseBody by default is applied on all resources in that controller.
Refer this link: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

The problem you are facing is because the returned object(JSONObject) does not have getter for certain properties. And your intention is not to serialize this JSONObject but instead to serialize a POJO. So just return the POJO.
Refer this link: https://stackoverflow.com/a/35822500/5039001

If you want to return a json serialized string then just return the string. Spring will use StringHttpMessageConverter instead of JSON converter in this case.

2 of 10
130

The reason why your current approach doesn't work is because Jackson is used by default to serialize and to deserialize objects. However, it doesn't know how to serialize the JSONObject. If you want to create a dynamic JSON structure, you can use a Map, for example:

@GetMapping
public Map<String, String> sayHello() {
    HashMap<String, String> map = new HashMap<>();
    map.put("key", "value");
    map.put("foo", "bar");
    map.put("aa", "bb");
    return map;
}

This will lead to the following JSON response:

{ "key": "value", "foo": "bar", "aa": "bb" }

This is a bit limited, since it may become a bit more difficult to add child objects. Jackson has its own mechanism though, using ObjectNode and ArrayNode. To use it, you have to autowire ObjectMapper in your service/controller. Then you can use:

@GetMapping
public ObjectNode sayHello() {
    ObjectNode objectNode = mapper.createObjectNode();
    objectNode.put("key", "value");
    objectNode.put("foo", "bar");
    objectNode.put("number", 42);
    return objectNode;
}

This approach allows you to add child objects, arrays, and use all various types.

🌐
Moss GU
mossgreen.github.io › JSON-in-spring-boot
Returning JSON in Spring Boot - Moss GU
August 3, 2018 - In Sprint Boot, REST controller returns JSON obect in the response body. Reason is that Spring implicitely uses message converter MappingJackson2HttpMessageConverter, which handles the conversion of Object to JSON format if the request’s Accept ...
Discussions

How to output response in JSON format ? newbie Spring boot here
Spring serializes (making a string out of an object) response objects automatically. So if you have for example: @GetMapping("/whatever) Public WhateverResponse getWhatever() {.... } It will serialized it automatically for you. You just need to create the response object BTW not sure you're response object makes sense You have to fields of the same object, it's better to make it an array { "locations": [ { "postal" :... } ] Other fields... } And the response class should be Class Response { List locations; Other fields... } Class Location { private String postal; Other fieldsl } More on reddit.com
🌐 r/SpringBoot
5
1
September 27, 2023
java - How to return JSON response in Springboot? - Stack Overflow
I want to return json response something like this in spring boot : { "status" : true, "message" : "Data is found", "data" : single object or list of More on stackoverflow.com
🌐 stackoverflow.com
java - Return JSON object from a spring-boot rest Controller - Stack Overflow
If you are using the spring-boot-starter-web, your project is already set to return JSON. Instead of String as the return value from checkEmailUnique, use an object type that you create. More on stackoverflow.com
🌐 stackoverflow.com
June 21, 2018
How to convert object to json in controller?
Spring will do it for you. Just create a separate controller and annotate the class with @RestController. Then just return your object or list of objects in your controller method. Spring will automatically use Jackson to serialize it to JSON. More on reddit.com
🌐 r/SpringBoot
6
6
September 2, 2022
🌐
ilhicas
ilhicas.com › 2019 › 04 › 27 › Returning-JSON-object-as-response-in-Spring-Boot.html
Returning JSON object as response in Spring Boot when returning Entity | ilhicas
April 26, 2019 - So, given that Springboot uses Jackson by default to convert our Entity Object to JSON to return when using @RestController we can make use of Jackson Annotations: @JsonIgnore and @JsonProperty · So now lets annotate our JsonObject with @JsonIgnore to avoid serializing that specific attribute ...
🌐
Reddit
reddit.com › r/springboot › how to output response in json format ? newbie spring boot here
r/SpringBoot on Reddit: How to output response in JSON format ? newbie Spring boot here
September 27, 2023 -

Hey I want my service to return something like :

{
    "location1": {
        "postal_code": "AB12 3CD",
        "latitude": 51.12345,
        "longitude": -0.67890
    },
    "location2": {
        "postal_code": "EF45 6GH",
        "latitude": 52.23456,
        "longitude": -1.78901
    },
    "distance": 123.45,
    "unit": "km"
}

so my service supposed to be calculate distance between two locations and display response as above. How to create the service and restcontroller method?

Do we need to use Map<String, Object> in service method to output the response? please guide me

Top answer
1 of 3
1
Spring serializes (making a string out of an object) response objects automatically. So if you have for example: @GetMapping("/whatever) Public WhateverResponse getWhatever() {.... } It will serialized it automatically for you. You just need to create the response object BTW not sure you're response object makes sense You have to fields of the same object, it's better to make it an array { "locations": [ { "postal" :... } ] Other fields... } And the response class should be Class Response { List locations; Other fields... } Class Location { private String postal; Other fieldsl }
2 of 3
1
You don't explain exactly what you are expecting here. Or at least, I am unclear. In this sort of application you have a POST request method that takes an object which has been passed to it by the caller. The callser sends this as a JSON body to the request and spring boot will do the translation to a java POJO. You then call the service with this do calculate the distance - eiter a road route or a great circle calculation. If its the later, I can help with that! Assuming that you are looking for how the request should be structured, its quite simple. Ignore the fact that this is JSON and simply describe the data structures you need. Let Spring Boot handle all that nasty mapping nonsence for you! Here I suggest some data structures and the REST call. The details of what happens in the service are left to you. Of course, this will need some refactoring to put the classes in to separate files. public class Location { String post_code; Double lattitude; Double Longitude; } public class Data { Location location1; Location location2: Double distance; String: unit; } @PostMapping("/distance") public Data calcDistance(@RequestBody Data mydata) { return myService.calcDistance(mydata); }
🌐
Springjavalab
springjavalab.com › 2025 › 05 › spring-boot-return-json-responses.html
How to Return JSON Responses in Spring REST APIs
When you annotate your class with @RestController, Spring automatically converts your returned object to JSON. Copy · @RestController @RequestMapping("/api/employees") public class EmployeeController { @GetMapping("/{id}") public Employee getEmployee(@PathVariable Long id) { return new ...
🌐
Spring
docs.spring.io › spring-boot › docs › 2.3.0.M4 › api › org › springframework › boot › configurationprocessor › json › JSONObject.html
JSONObject (Spring Boot 2.3.0.M4 API)
April 20, 2023 - Returns an array containing the string names in this object. This method returns null if this object contains no mappings. ... Encodes the number as a JSON string.
🌐
Baeldung
baeldung.com › home › spring › spring boot › spring boot consuming and producing json
Spring Boot Consuming and Producing JSON | Baeldung
February 19, 2026 - Writing a JSON REST service in Spring Boot is simple, as that’s its default opinion when Jackson is on the classpath: @RestController @RequestMapping("/students") public class StudentController { private final StudentService service; public StudentController(StudentService service) { this.service = service; } @GetMapping("/{id}") public Student read(@PathVariable(name = "id) String id) { return service.find(id); } ...
Find elsewhere
🌐
Spring
docs.spring.io › spring-boot › docs › 2.3.0.M2 › api › org › springframework › boot › configurationprocessor › json › JSONObject.html
JSONObject (Spring Boot 2.3.0.M2 API)
Returns an array containing the string names in this object. This method returns null if this object contains no mappings. ... Encodes the number as a JSON string.
🌐
DEV Community
dev.to › ayshriv › spring-boot-rest-api-returning-response-in-json-format-4db0
Spring Boot REST API - Returning Response in JSON Format - DEV Community
February 23, 2025 - ✅ Used Jackson for JSON serialization (default in Spring Boot). ✅ Created a DTO class for structured JSON responses. ✅ Developed a REST API that returns JSON using produces = MediaType.APPLICATION_JSON_VALUE.
🌐
CodeSignal
codesignal.com › learn › courses › building-restful-apis-with-spring-boot-1 › lessons › returning-json-responses-in-spring-boot
Returning JSON Responses in Spring Boot
Each time you send a GET request ... library called Jackson to perform this serialization seamlessly. Jackson takes your Kotlin objects and, through a series of configurations and rules, converts them into JSON....
🌐
GeeksforGeeks
geeksforgeeks.org › spring-rest-json-response
Spring - REST JSON Response - GeeksforGeeks
March 24, 2025 - It exists as a string and needs to be converted into a native Javascript object to access the data by available global JSON methods of Javascript. ... To create a Spring Boot application that handles JSON responses, we need to include the ...
🌐
Medium
medium.com › @AlexanderObregon › customizing-json-responses-in-spring-boot-apis-a3735056cbd1
Customizing JSON Responses in Spring Boot APIs | Medium
May 16, 2025 - Any time your controller returns an object, Jackson takes over and turns that object into a JSON string. It does that by checking your class structure and any annotations you’ve added.
🌐
Medium
rameshfadatare.medium.com › spring-boot-rest-api-that-returns-list-of-java-objects-in-json-format-503a01a00015
Chapter 14: Spring Boot REST API That Returns a List of Java Objects in JSON Format | Spring Boot Course | by Ramesh Fadatare | Medium
April 23, 2025 - This chapter is a continuation of Spring Boot REST API That Returns JSON. ... package com.company.restapi.controller; import com.company.restapi.model.Student; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.List; @RestController public class StudentController { @GetMapping("/student") public Student getStudent() { return new Student(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com"); } @GetMapping("/students") public List<Student> getAllStudents() { return Arrays.asList( new Student(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com"), new Student(2L, "Suresh", "Kumar", "suresh.kumar@example.com"), new Student(3L, "Mahesh", "Yadav", "mahesh.yadav@example.com") ); } }
🌐
HowToDoInJava
howtodoinjava.com › home › spring rest › json example
Spring REST Hello World JSON Example
December 19, 2021 - The @ResponseBody annotation tells the controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
🌐
Spring
docs.spring.io › spring-boot › docs › 2.3.0.RC1 › api › › org › springframework › boot › configurationprocessor › json › JSONObject.html
JSONObject (Spring Boot 2.3.0.RC1 API)
Returns an array containing the string names in this object. This method returns null if this object contains no mappings. ... Encodes the number as a JSON string.
🌐
ZetCode
zetcode.com › springboot › json
Spring Boot JSON - serving JSON data in a Spring Boot annotation
July 28, 2023 - The spring-boot-starter-json is pulled with the spring-boot-starter-web. In Spring objects are automatically convered to JSON with the Jackson library. Spring can be configured to convert to XML as well.
🌐
Reddit
reddit.com › r/springboot › how to convert object to json in controller?
r/SpringBoot on Reddit: How to convert object to json in controller?
September 2, 2022 -

My project uses spring data embers for auditing and I would like users to be able to see the data in the auditing table using a controller endpoint. So something like “/audit/2” would give produce a JSON array with the auditing history of the model object that has an id of 2.

My repository class extends RevisionRepository and gives me some methods I can work with like findRevisions(id).

My question is how do I convert the output of this method (which is a Revision object) into a JSON array? Do I need a DTO to manually get its fields from the Revision object or is there an easier way?

🌐
Java67
java67.com › 2023 › 04 › how-to-accept-and-produce-json-as.html
How to Accept and Produce JSON as a response in Spring Boot? Example Tutorial | Java67
Just return a POJO, and the Jackson serializer will handle the JSON conversion by itself. When used in conjunction with @Controller, it is the same as using ResponseBody. We use @RestController in place of the standard @Controller, and @ResponseBody ...