F
F
Fedor unknown2021-08-18 00:50:10
Java
Fedor unknown, 2021-08-18 00:50:10

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:
611c2e2de7857998845094.png

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>


code:
controller
@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:
@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;
}

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-08-18
@turdubekov

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);
      }
   }

Here is an example dto structure for xml 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 question

Ask a Question

731 491 924 answers to any question