- Customizing RESTful JSON Response – Spring Boot
- Table of Contents
- Create REST service with spring boot
- Create the DTO class
- Create a controller class
- Retrieve the EmployeeDTO
- Customizing the JSON response
- Conclusion
- How to Get Response as Json With Responseentity in Java
- ResponseEntity do not return json response for Post Method
- How can I get the json file from ResponseEntity?
- Spring Rest return a JSON response with a certain http response code
- How I do it
- A different story
- Spring Boot: Testing ResponseEntity Containing Java Time
- Работа с JSON и XML (преобразование объектов) в Spring MVC. Формирование ответа и обработка запроса
- 1. Описание задачи
- 2. Структура проекта
- 3. pom.xml
Customizing RESTful JSON Response – Spring Boot
Spring boot supports the development of RESTful APIs by providing good support. Spring boot’s web dependency adds Jackson libraries by default. We can easily customize the response JSON fields according to our requirements. Customizing the Restful JSON response with spring boot is a simple task.
In this article, we will learn how to override the default JSON response fields by using custom configurations.
We will also create a simple DTO class with few fields containing different data types like LocalDate, etc. Finally, we will expose a REST endpoint to retrieve the DTO object in the JSON form.
In the first part of the article, we will use the default Jackson properties and check how the response fields are without customization. In the later part of the article, we will customize the response according to our requirements.
Table of Contents
Create REST service with spring boot
We are going to create a simple spring boot application with spring-boot-starter-web and lombok(to avoid boilerplate code) dependencies.
Create the DTO class
A DTO class is a simple java POJO class with getter and setter methods. We will create a simple java class with the name EmployeeDTO with few fields as shown below.
This DTO class contains fields of different types like String, Date of type java.util library and LocalDate, LocalDateTime, etc.
We have used the Lombok library to avoid extra boilerplate codes to generate getter, setter, and other methods.
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString public class EmployeeDTO
Create a controller class
Create a RESTful controller java class with the name EmployeeController. Also, create an HTTP GET endpoint at the URL path /get-json as shown below.
The getObject() method defined below, when invoked, returns a new EmployeeDTO object.
@RestController public class EmployeeController < @GetMapping("/get-json") public ResponseEntitygetObject() < EmployeeDTO dto = new EmployeeDTO(1, "Arun", new Date() ,LocalDate.now(), LocalDateTime.now()); return new ResponseEntity<>(dto, HttpStatus.OK); > >
Retrieve the EmployeeDTO
Since we haven’t made any changes in the default Jackson configuration, we will get the below JSON response.
Customizing the JSON response
Suppose we have a requirement to change the JSON response, with all field names that should be followed underscores, instead of camel cases. Also, date fields should have a particular date format.
This can be achieved by creating a configuration class, implementing the WebMvcConfigurer interface, and overriding the configureMessageConverters() method. This will also override the default message converter behavior of the current application.
We also need to use the @EnableWebMvc annotation on our configuration class.
Create a java configuration class with the name CustomJsonConfig and implement the WebMvcConfigurer interface. Annotate the class with the @EnableWebMvc and the @Configuration annotations.
The below code shows the complete code of the configuration class.
@Configuration @EnableWebMvc public class CustomJsonConfig implements WebMvcConfigurer < @Value("$") private String test; @Override public void configureMessageConverters(List> converters) < ObjectMapper mapper = new Jackson2ObjectMapperBuilder() .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) .simpleDateFormat(test.equalsIgnoreCase("A") ? "MM/dd/yyyy" : "MM-dd-yyyy") .serializers( new LocalDateSerializer(test.equalsIgnoreCase("A") ? DateTimeFormatter.ofPattern("yyyy/MM/dd") : DateTimeFormatter.ofPattern("dd-MM-yyyy")), new LocalDateTimeSerializer( test.equalsIgnoreCase("A") ? DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") : DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"))) .deserializers( new LocalDateDeserializer(test.equalsIgnoreCase("A") ? DateTimeFormatter.ofPattern("yyyy/MM/dd") : DateTimeFormatter.ofPattern("dd-MM-yyyy")), new LocalDateTimeDeserializer( test.equalsIgnoreCase("A") ? DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") : DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"))) .build(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(mapper); converters.add(converter); >>
Also, add the following property to the application.properties file.
In the above code, we have set the property naming strategy to SNAKE_CASE, which converts the camel-case DTO field names into underscore separated names.
We can also see a SPEL(Spring Expression Language) expression, which reads the dateformat.type property and sets it to the field called test.
We are setting the date-time format dynamically based on the value of the custom property dateformat.type.
If the property value is A, the java.util.Date field is set with date format MM/dd/yyyy and the date format will be MM-dd-yyyy for any other values.
Similarly, we have configured different LocalDate and LocalDateTime formats based on the value of the dateformat.type property dynamically.
Below is the customized JSON output with the dateformat.type property value as “A“.
Congratulations!! 🙂 We have learned how to customize RESTful service response JSON by overriding the default message converter properties.
Conclusion
In this article, we learned about customizing the JSON response of spring boot RESTful web service applications.
We also learned how to dynamically set the JSON properties by customizing the date format of the response JSON based on the configuration property value.
The sample code is available on Github.
How to Get Response as Json With Responseentity in Java
ResponseEntity do not return json response for Post Method
You have A_VALUE and B_VALUE as attributes in your class whereas you’re setting values of a_value and b_value.
Do Autowire your PostService class and also remove these(Jackson) dependencies when you have starter-web dependency already. I would also recommend you to use Lombok’s @Data and @NoArgsConstructor annotations at class level.
How can I get the json file from ResponseEntity?
Change the Response type from getForObject to String.class , then, use the BufferedWriter to write the file.
RestTemplate rest = new RestTemplate();
String response = rest.getForObject("http://example.com/", String.class);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
writer.append(response);
writer.close();
The RestTemplate#exchange returns a ResponseEntity , not a String .
In your case, it will return a ResponseEntity .
That’s why you’re unable to write the object. To do so, you need to get the body from the ResponseEntity object. Use the method ResponseEntity#getBody
ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, request, String.class, 1);
BufferedWriter writer = new BufferedWriter(new FileWriter("my-file.json", true));
// here you are getting the String with the response.getBody() method,
// so buffered writer can write the file
writer.append(response.getBody());
writer.close();
Spring Rest return a JSON response with a certain http response code
How I do it
Here is how I do JSON returns from a Spring Handler method.
My techniques are somewhat out-of-date,
but are still reasonable.
Configure Jackson
Add the following to the spring configuration xml file:
With that,
Spring will convert return values to JSON and place them in the body of the response.
Create a utility method to build the ResponseEntity
Odds are good that you will have multiple handler methods.
Instead of boilerplate code,
create a method to do the standard work.
ResponseEntity is a Spring class.
protected ResponseEntity buildResponse(
final ResponseJson jsonResponseBody,
final HttpStatus httpStatus)
final ResponseEntity returnValue;
if ((jsonResponseBody != null) &&
(httpStatus != null))
returnValue = new ResponseEntity<>(
jsonResponseBody,
httpStatus);
>
return returnValue;
>
Annotate the handler method
@RequestMapping(value = "/webServiceUri", method = RequestMethod.POST)
you can also use the @PostMethod annotation
Return ResponseEntity from the handler method
Call the utility method to build the ResponseEntity
public ResponseEntity handlerMethod(
. params)
. stuff
return buildResponse(json, httpStatus);
>
Annotate the handler parameters
Jackson will convert from json to the parameter type when you use the @RequestBody annotation.
public ResponseEntity handlerMethod(
final WebRequest webRequest,
@RequestBody final InputJson inputJson)
. stuff
>
A different story
You can use the @JsonView annotation.
Check out the Spring Reference for details about this.
Browse to the ref page and search for @JsonView.
Spring Boot: Testing ResponseEntity Containing Java Time
Explanation
Here you are instantiating the timestamp field at two different times and comparing them. They will always fail to match.
I would recommend avoiding the instantiation of new ApiError(HttpStatus.BAD_REQUEST) in your test and simply verifying each field individually. For the timestamp field, just verify that it is set to a non-null value or if you want to get pedantic, verify that it has a value within the last X number of seconds instead of the precise millisecond validation that you are currently checking.
Alternative Solution (Hacky Workaround)
If you want to continue validation a JSON string against a JSON string, simply convert the response body into an object and steal it’s timestamp into your comparison object.
Работа с JSON и XML (преобразование объектов) в Spring MVC. Формирование ответа и обработка запроса
Работа с JSON и XML (преобразование объектов) в Spring MVC. Формирование ответа и обработка запроса (RESTful веб-сервис). Применение RestTemplate в Spring MVC.
Обзор приложения Spring MVC + AngularJS + Bootstrap + HTML5
Используемые технологии и библиотеки
1. Описание задачи
В этой части будет рассмотрена работа приложения Spring MVC с форматами JSON и XML (RESTful веб-сервис). Будет показана возможность преобразовывать Java объекты в эти форматы, а так же формировать ответ в JSON или XML виде на запрос клиента. Для примера будет использован сторонний источник данных (внешний интернет ресурс), который будет предоставлять данные в том или ином формате. Таким образом здесь мы рассмотрим:
- Преобразование POJO (Plain Old Java Object) объектов в формат XML
- Преобразование POJO объектов в формат JSON
- Использование аннотаций @ResponseBody , @RestController , @XmlRootElement , @XmlElement
- Использование RestTemplate
2. Структура проекта
Классы находятся в пакете rest. Во вложенном пакете model находятся классы объектов, которые мы будем преобразовывать в XML или JSON формат ( DBLogJSON , DBLogsXML , RestPostsModel , RestUserModel и т.д.). На уровень выше находятся два контроллера ( RestController и RestTemplateController ), которые будут демонстрировать различные способы работы с REST сервисами. Например, класс RestTemplateController обращается к внешнему сайту (http://jsonplaceholder.typicode.com), который возвращает данные в ответ на запросы, посылаемые нашим приложением.
Создан один файл представление — rest.jsp из одноименного пакета. На этой страничке будет доступен вызов того или иного метода из контроллеров.
3. pom.xml
Отдельной строкой была добавлена зависимость Java Architecture for XML Binding (JAXB). Этот пакет входит в Java SE и можно было бы его не добавлять для этого проекта, но здесь было выделить его в учебных целях.