Leanid Herasimau Leanid Herasimau - 1 month ago 16
Java Question

Spring Boot Response Entity doesn't return JSON

When i return my POJO from RestController it's transforms in JSON object.
But when i try to return

new ResponseEntity<>("success", HttpStatus.CREATED);

controller returns plain-text. What's wrong?

My RestController:

@RequestMapping(value = "/register", method = RequestMethod.POST,consumes = "application/json", produces="application/json")
public ResponseEntity<?> registerUser(@RequestBody User user) throws MessagingException {
if(registrationService.canRegister(user.getEmail())){
registrationService.registerUser(user);
logger.info("Registered user "+user.getEmail());
return new ResponseEntity<>("success", HttpStatus.CREATED);
}
return new ResponseEntity<>(HttpStatus.CONFLICT);
}


My dependencies:

<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>


Spring Boot version 1.4.1

Answer

"success" as a String cannot be cast to JSON format. Hence, spring controller returns plain/text.Generally, for any object to be cast as JSON, it must be in the format of a key value pair, so all POJOs can be converted to corresponding key-value pairs where key is the property name and value is property's value. You can have a look at this page to validate what constitutes a valid json. https://jsonformatter.curiousconcept.com/

Comments