@Responsebody , Responseentity Spring Return Object as Json

@ResponseBody , ResponseEntity Spring return Object as JSON

@RestController itself adds @ResponseBody annotation. You can see it in the Github Issue

You can also check the official spring tutorials. Here you can check the below lines and examples:

These controller methods return simple POJOs - Collection<Bookmark>,
and Bookmark, etc., in all but the add case. When an HTTP request
comes in that specifies an Accept header, Spring MVC loops through the
configured HttpMessageConverter until it finds one that can convert
from the POJO domain model types into the content-type specified in
the Accept header, if so configured.

You can also follow the below lines and examples from Official doc

@RestController is a stereotype annotation that combines @ResponseBody
and @Controller. More than that, it gives more meaning to your
Controller and also may carry additional semantics in future releases
of the framework.


As with @RequestBody and @ResponseBody, Spring uses
HttpMessageConverter to convert from and to the request and response

Spring Boot : How to pass errors through JSON response?

RestTemplate will throw an exception for any error responses. You can surround the template.getForEntity call in a try-catch block and handle the exceptions, returning the message in any format you want.

The exception you are looking for is HttpStatusCodeException.

Migrating @ResponseBody to ResponseEntity

According to the javadoc for @RequestMapping (https://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html), the body of the ResponseEntity will be unwrapped and written to the response output stream. So the output should be the same.

Documentation for the current release (https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-return-types) says essentially the same thing.

How to return Bean class Object as JSON in Rest Controller in Spring MVC

add dependency in pom.xml



Write one method in controller.

public String toJson(User bean) { 
return new JSONSerializer().transform(new DateTransformer("MM/dd/yyyy HH:mm:ss"),java.util.Date.class).serialize(bean);

and pass your bean object to this method.

return new ResponseEntity<String>(toJson(bean),headers, HttpStatus.CREATED); 

change return type to string in method signature public ResponseEntity<String> callRequest

NOTE: For Spring boot you can use @RestController annotation which will auto convert objects to json.

Related Topics

Leave a reply