FasterXML / FasterXML/jackson-future-ideas

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

Open
#67 2 comments 18 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
21
Forks
3
PR merge metrics
No merged PRs in 30d

Description

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.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.