Answer the question
In order to leave comments, you need to log in
How to process the received POST request with a JSON body and return the response in the form of XML?
Good morning!
Question: How can a POST request with a JSON body be processed and returned as an XML response?
1. I receive json, but I don’t know how to process it and return it as XML
, what I get is:
And it should be:
<?xml version="1.0" encoding="UTF-8" ?>
<response id="123123123" dts="2021-04-10 01:01:01">
<p_id>111222</p_id>
<status>1</status>
<message>PAYMENT CONFIRMED</message>
</response>
@RestController
@RequestMapping(path = "/")
@RequiredArgsConstructor
public class RequestController{
private final RequestServiceImpl service;
@PostMapping(path = "/save",
produces = {"application/xml", "text/xml"}, consumes =
MediaType.ALL_VALUE)
public ResponseEntity<Request> pay(@RequestBody Request request){
service.save(request);
return ResponseEntity.ok(request);
}
}
@Entity
@Getter
@Setter
@NoArgsConstructor
@XmlRootElement
public class Request {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long supplierId;
private String account;
private Long amount;
@Enumerated(EnumType.STRING)
private Command command;
private LocalDateTime date;
}
Answer the question
In order to leave comments, you need to log in
Good afternoon.
You must have 2 DTOs.
1 - to get json from a POST request.
2 - to return xml in response.
After processing the json, you need some kind of mapper (you can use the interface Converter<S,T>
) that will convert your Request to Response.
It should be something like this:
@PostMapping(path = "/save",
produces = {"application/xml", "text/xml"}, consumes =
MediaType.ALL_VALUE)
public ResponseEntity<Response> pay(@RequestBody Request request){
service.save(request);
// тут конвертируем request в response
return ResponseEntity.ok(response);
}
}
public class response {
public int p_id;
public int status;
public String message;
public int id;
public Date dts;
public String text;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question