Skip to content

Commit df095d5

Browse files
Added more documentation for Builder (#3620)
1 parent 6e53001 commit df095d5

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

README.md

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ assertEquals(23, person.getAge().intValue());
452452

453453
If your builder pattern implementation uses other prefixes for methods or uses other names than build() for the builder method Jackson also provide a handy way for you.
454454

455-
For example, if you have a builder class uses the "set" prefix for its methods and use the create() method instead of build() for building the whole class, you have to annotate your class like:
455+
For example, if you have a builder class that uses the "set" prefix for its methods and use the create() method instead of build() for building the whole class, you have to annotate your class like:
456456
```java
457457
@JsonPOJOBuilder(buildMethodName = "create", withPrefix = "set")
458458
static class Builder {
@@ -475,6 +475,35 @@ static class Builder {
475475
}
476476
```
477477

478+
To deserialize JSON fields under a different name than their object counterparts,
479+
the @JsonProperty annotation can be used within the builder on the appropriate fields.
480+
481+
```java
482+
@JsonPOJOBuilder(buildMethodName = "create", withPrefix = "set")
483+
static class Builder {
484+
@JsonProperty("known_as")
485+
String name;
486+
Integer age;
487+
//...
488+
}
489+
```
490+
This will deserialize the JSON property `known_as` into the builder field `name`. If a mapping like this is not provided (and further annotations aren't supplied to handle this), an `Unrecognized field "known_as"` exception will be thrown during deserialization if the field is provided anyways.
491+
492+
If you wish to refer to properties with more than one alias for deserialization, the `@JsonAlias` annotation can be used.
493+
494+
```java
495+
@JsonPOJOBuilder(buildMethodName = "create", withPrefix = "set")
496+
static class Builder {
497+
@JsonProperty("known_as")
498+
@JsonAlias({"identifier", "first_name"})
499+
String name;
500+
Integer age;
501+
//...
502+
}
503+
```
504+
This will deserialize JSON fields with `known_as`, as well as `identifer` and `first_name` into `name`. Rather than an array of entries, a single alias can be used by specifying a string as such `JsonAlias("identifier")`.
505+
Note: to use the `@JsonAlias` annotation, a `@JsonProperty` annotation must also be used.
506+
478507

479508

480509

0 commit comments

Comments
 (0)