Thiago Salgado
Thiago Salgado

Reputation: 27

Serialize entity into DTO using SpringBoot and Lombok

I currently recieve a POST request with a JSON that is serialized into Cobranca entity by SpringBoot with lombrok getter and setter.

I want to serialize this entity into a CobrancaDTO that latter will generate a second JSON with a different hierarchy model.

How would I be able to serialize the entity Cobranca into my CobrancaDTO, since CobrancaDTO has a different hierarchy model? Should I somehow use a custom ObjectMapper? Or should I just populate the DTO with a method, populating it property by property?

Cobranca entity already serialized

CobrancaDTO model

Upvotes: 0

Views: 1418

Answers (1)

Jan Rieke
Jan Rieke

Reputation: 8112

You have two different concerns here, which are (de)serialization and mapping. I strongly advise not to mix those.

I suggest that you first deserialize your incoming JSON payload into instances of a (input) DTO class that exactly reflects the (input) JSON structure. (By default, Spring uses Jackson for this purpose.)

Next, you map these to another (output) DTO class, which reflects the desired output JSON structure. You can use a framework like MapStruct for this. Finally, you simply serialize the (output) DTO objects.

Upvotes: 1

Related Questions