How to change the structure of a JSON serialized with Jackson in an DTO of a Panache/Hibernate Entity?

66 views Asked by At

I have those two entities defined in my app:

@Entity
public class Avail extends PanacheEntity {
    public Integer total;
    public Integer limit;
    @JsonProperty("last_transactions")
    @OneToMany(
        mappedBy = "avail",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    public <List<Transactions> transactions = new LinkedList<>();
@Entity
public class Transactions extends PanacheEntityBase {
    public Integer value;
    public String type;
    public String description;
    @JsonProperty("datetime")
    public String ts;
    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    public Avail avail;

And this DTO to provide a response as application/json:

@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
@JsonTypeName("avail")
@JsonPropertyOrder({ "total", "dataExtrato", "limit" })
public final class AvailDTO {

    public final Integer total;
    @JsonProperty("data_extrato")
    public final String dataExtrato;
    public final Integer limit;
    @JsonProperty("last_transactions")
    public final List<Transactions> transactions;

Those classes generates this response:

{
"avail": {
"total": 29000,
"data_extrato": "2024-02-24T11:50:15.294900Z",
"limit": 100000,
"last_transactions": \[{
"value": 21000,
"type": "d",
"description": "withdraw",
"datetime": "2024-02-24T14:46:00.904000300Z"
}, {
"value": 50000,
"type": "c",
"description": "deposit",
"datetime": "2024-02-24T14:46:17.837816Z"
}\]
}
}

But I need the response to look like this (with "last_transactions" outside "avail"):

{
"avail": {
"total": 29000,
"data_extrato": "2024-02-24T11:50:15.294900Z",
"limit": 100000,
},
"last_transactions": \[{
"value": 21000,
"type": "d",
"description": "withdraw",
"datetime": "2024-02-24T14:46:00.904000300Z"
}, {
"value": 50000,
"type": "c",
"description": "deposit",
"datetime": "2024-02-24T14:46:17.837816Z"
}\]

}

Couldn't figure out how to properly code my DTO to change the JSON structure.

1

There are 1 answers

0
Márcio C Goulart On

I managed to create another DTO with 2 properties, which wraps AvailDTO on a property and set a list of transactions on the other. Probably not the most elegant solution, but it worked. Code can be viewed at https://github.com/marciocg/rinhaquarkus/tree/main/src/main/java/io/github/marciocg/clientes