I tried with your code with a sample spring boot project and I get the error,

No converter for [class org.json.JSONObject]

The reason for this error is explained clearly here. To reiterate the answer, JSONObject classes don't have getters and hence the error. By default spring-boot starter web dependency has Jackson web support which can convert any POJO class to JSON object. So as the answer by @süleyman-can using a POJO is the right way to handle this.

In case, you can't use a POJO class because the fields in the response will be different for each request. For example, you have to send

{"a": "b"}

for one response and

{"c": "d"}

for another response, you can always use Map<String, String> like this,

@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public Map<String, String> test() {
  Map<String, String> test = new HashMap<>();
  test.put("name","caroline");
  return test;
}

and the response would come like this,

{"name":"caroline"}                                                                                                                      
Answer from Malathi on Stack Overflow
🌐
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)
Creates a new JSONObject with name/value mappings from the next object in the tokener. ... JSONException - if the parse fails or doesn't yield a JSONObject.
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.

🌐
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)
Creates a new JSONObject with name/value mappings from the next object in the tokener. ... JSONException - if the parse fails or doesn't yield a JSONObject.
🌐
Spring
docs.spring.io › spring-boot › docs › 2.3.0.M1 › api › org › springframework › boot › configurationprocessor › json › JSONObject.html
JSONObject (Spring Boot 2.3.0.M1 API)
Creates a new JSONObject with name/value mappings from the next object in the tokener. ... JSONException - if the parse fails or doesn't yield a JSONObject.
🌐
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)
Creates a new JSONObject with name/value mappings from the next object in the tokener. ... JSONException - if the parse fails or doesn't yield a JSONObject.
🌐
TutorialsPoint
tutorialspoint.com › springmvc › springmvc_json.htm
Spring MVC - Generate JSON Example
Here, we have created a Simple POJO User and in UserController we have returned the User. Spring automatically handles the JSON conversion based on RequestMapping and Jackson jar present in the classpath.
🌐
Baeldung
baeldung.com › home › spring › spring boot › spring boot consuming and producing json
Spring Boot Consuming and Producing JSON | Baeldung
March 21, 2019 - Learn how to consume and produce JSON content in a typical CRUD REST service developed with a Spring Boot.
Find elsewhere
🌐
Java Guides
javaguides.net › 2019 › 07 › java-create-json-example-json.html
Java Create JSON Example - JSON Processing API
July 16, 2019 - In this post, we will learn how to create a JSON object from Java object using JSON-P library. Check out complete JSON-P tutorial at Java JSON Processing Tutorial.
🌐
YouTube
youtube.com › intellipaat
Spring Boot Tutorial Part-3 | JSON Object | REST API Web Services Tutorial | Intellipaat - YouTube
This video on “Spring Boot” will take you to the next level of your journey of learning Spring Boot. In this video, you will first get the hands-On JSON Obje...
Published   December 1, 2022
Views   2K
🌐
Attacomsian
attacomsian.com › blog › jackson-create-json-object
How to create a JSON Object using Jackson
October 14, 2022 - The above code generates the following JSON object: { "id" : 1, "name" : "John Doe", "email" : "john.doe@example.com", "salary" : 3545.99, "role" : "QA Engineer", "admin" : false, "address" : { "street" : "2389 Radford Street", "city" : "Horton", "state" : "KS", "zipCode" : 66439 } } For more Jackson examples, check out the How to read and write JSON using Jackson in Java tutorial.
🌐
ZetCode
zetcode.com › springboot › json
Spring Boot JSON - serving JSON data in a Spring Boot annotation
Spring Boot JSON tutorial shows how to serve JSON data in a Spring Boot annotation. JSON (JavaScript Object Notation) is a lightweight data-interchange format.
🌐
Spring
docs.spring.io › spring-boot › docs › 2.3.0.M3 › api › org › springframework › boot › configurationprocessor › json › JSONObject.html
JSONObject (Spring Boot 2.3.0.M3 API)
Creates a new JSONObject with name/value mappings from the next object in the tokener. ... JSONException - if the parse fails or doesn't yield a JSONObject.
🌐
Aviator Dao
java2novice.com › главная страница › welcome to aviator dao from the creators of the java2novice
How to create Json Object using Object Model?
July 22, 2024 - Discover the evolution of our journey from Java programming tutorials to the exciting world of the Aviator Game. At Aviator DAO, we provide in-depth guides, strategies, and resources for mastering Aviator.
🌐
DZone
dzone.com › coding › frameworks › create a json api rest service with spring boot and elide
Create a JSON API REST Service With Spring Boot and Elide
February 11, 2016 - One of these libraries is Elide, ... expose Java JPA entities through a JSON API compatible interface. The nice thing about Elide is if you already have JPA entities, then with just a few lines of code you can expose them through a JSON API REST interface. To demonstrate this, I’m going to show you how to build a read-only JSON API RESTful service using JPA, Elide and Spring Boot...
🌐
Spring
docs.spring.io › spring-boot › reference › features › json.html
JSON :: Spring Boot
import tools.jackson.core.JsonGenerator import tools.jackson.core.JsonParser import tools.jackson.databind.DeserializationContext import tools.jackson.databind.JsonNode import tools.jackson.databind.SerializationContext import org.springframework.boot.jackson.JacksonComponent; import org.springframework.boot.jackson.ObjectValueDeserializer import org.springframework.boot.jackson.ObjectValueSerializer @JacksonComponent class MyJacksonComponent { class Serializer : ObjectValueSerializer<MyObject>() { override fun serializeObject(value: MyObject, jgen: JsonGenerator, context: SerializationContext
🌐
Baeldung
baeldung.com › home › json › introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system: >> Flexible Pub/Sub Messaging With Spring Boot and Dapr · JSON (JavaScript Object Notation) is a lightweight data-interchange format, and we most commonly ...
🌐
Medium
satyacodes.medium.com › springboot-export-java-objects-to-json-json-to-object-7f6d4208ed64
SpringBoot — export Java Objects to JSON & JSON to Object | by Satya Kaveti | Medium
November 6, 2023 - ObjectMapper mapper = new ObjectMapper(); //Java Object -> JSON String json = mapper.writeValueAsString(employeeDto); //JSON -> Java Object EmployeeDto dto = mapper.readValue(json, EmployeeDto.class);
🌐
HowToDoInJava
howtodoinjava.com › home › spring boot › spring boot rest: consuming and producing json
Spring Boot REST: Consuming and Producing JSON
November 25, 2023 - Similarly, when JSON data is received in a request, Spring Boot automatically converts it into the corresponding Java object. @PostMapping public Product createProduct(@RequestBody Product product) { // Process the received JSON data (e.g., save to the database) return productService.createProduct(product); }