F
F
Fedor unknown2021-09-03 08:21:26
Java
Fedor unknown, 2021-09-03 08:21:26

What is the correct way to convert POJO to XML?

task: i have to get json and return response as xml.
to return xml I wrote in the MEDAITYPE controller:

@PostMapping(path = "/save", produces = {"application/xml", "text/xml"}, consumes = MediaType.ALL_VALUE)
    public Object pay(@RequestBody Request request) {
        logger.info("Вызван метод: Pay");
        return service.add(request);
    }


pojo:
@Entity
@Getter
@Setter
@NoArgsConstructor
public class Request {

    @Id
    private Long id;

    private Long supplierId;

    private String account;

    private Long amount;

    @Enumerated(EnumType.STRING)
    private Command command;

    @Timestamp
    private LocalDateTime date;

}


I accept json:
PAY REQUEST:
{
  "request": {
    "id": 123123123,
    "supplier_id": 321321,
    "account": "999777111222",
    "amount": 100.12,
    "command": "pay",
  "date": "2021-04-10 01:01:01"
  }
}


what I can send back:
<SaveResponseDto>
    <response_id>777</response_id>
    <status>1</status>
    <message>PAYMENT CONFIRMED</message>
    <date>2021-08-18T00:48:02.4089693</date>
</SaveResponseDto>


the question is: how can it be correctly implemented in order to return XML in this form exactly like this:
<?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>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-09-03
Hasanly @azerphoenix

Good afternoon!
You have a dto - Request but no dto Response.
Here is an example pojo structure for Response ( source )

public class Response { 
  public int p_id;
  public int status;
  public String message;
  public int id;
  public Date dts;
  public String text;
}

Also, in order to return the response in xml, you need to add one library for jackson (if you use it).
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.11.1</version>
</dependency>

Details here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question