FasterXML / FasterXML/jackson-future-ideas

Support default values in Java 14 records (and POJOs too?)

Aperta
#67 2 commenti 18 reazioni 0 assegnatari Vedi su GitHub
Lingua principale
Nessun dato sulla lingua
Stelle
21
Fork
3
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Descrizione

It would be very useful in some situations to define default values when deserializing into a record. It is only possible in the moment to define default values using the `@JsonSetter` annotation and then define custom logic in the setter. But as this is not possible when using java records, as in this case all properties must be passed using the constructor and then the object becomes immutable.

It might be possible to use this:
```java
public record PageRequest(
int page,

int pageSize
) {
@JsonCreator
public PageRequest(
@JsonProperty("page") int page,
@JsonProperty("pageSize") Integer pageSize
) {
this(page, pageSize == null ? 20 : pageSize);
}
}
```

But the readability (especially when we have more than 2 properties) is not very good, and there is a lot of boilerplate code here. This variant might be much more readable:

```java
public record PageRequest(
int page,

@JsonProperty(defaultValue = "20") // this parameter already exists, just doesn't do anything in the moment
int pageSize
) {
}
```

or:
```java
public record PageRequest(
int page,

@JsonDefaultInt(20)
int pageSize
) {
}
```

This may also allow to handle default value in case the property is missing, so that it can still be set explicitly to `null`.

I know this ticket is kinda duplicated from #39 but I thought I may open a new one specifically related to java records and not only to default from `null` more to default when the property is missing.

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.