Pasha
Pasha

Reputation: 1912

How to make the best DTO request class?

I need to make a DTO class that represents a JSON request body.

I’d like to make it fully immutable with final fields. I’ve already seen implementations based on @JSONCreator all args constructor but I also require one more feature.

The DTO class should be flexible and tolerate some missing fields in a request meanwhile ensure that all necessary properties are in-place.

Could you provide me an example of such DTO, please?

Upvotes: 0

Views: 434

Answers (2)

Adwait Kumar
Adwait Kumar

Reputation: 1604

As @jbx pointed out that Jackson automatically handles missing fields and sets it to null.

If you want to ensure that required fields are populated, you need to mark those as @javax.annotation.Nonnull or lombok.NonNull.

Using this Jackson throws a NullPointerException if that field in null while de-serialization of request to DTO class.

Upvotes: 1

jbx
jbx

Reputation: 22128

Jackson will automatically handle missing fields and just set those fields to null.

It also has some configuration options on whether when serializing responses, null fields should be omitted or set to the special value null.

objectMapper.setSerializationInclusion(Include.NON_NULL);

On another note, if you are designing an API, you might want to look at Swagger / OpenAPI and define your API declaratively from there (you can specify whether a field is optional or required). Then use the codegen tools to automaticlly generate your DTOs. (They will follow the best patterns and also offer Fluent API style setters).

Upvotes: 2

Related Questions