Reputation: 61
Here's very simple scenario in which I got value object that I want to un-wrap for serialization. Using custom Serializer is not an option.
public class UnwrappedWithPropertyName {
public static void main(String[] args) throws JsonProcessingException {
final Address address = new Address(new Postcode("45678"));
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(address));
}
static class Address {
@JsonUnwrapped
@JsonProperty("postcode")
private final Postcode postcode;
Address(Postcode postcode) {
this.postcode = postcode;
}
public Postcode getPostcode() {
return postcode;
}
}
static class Postcode {
private final String value;
Postcode(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}
That will result in
{"value":"45678"}
and what I would expect is {"postcode":"45678"}
Upvotes: 0
Views: 1137
Reputation: 61
By annotating field with @JsonValue one can control the name of such field from enclosing class.
static class Address {
@JsonProperty("postcode")
private final Postcode postcode;
Address(Postcode postcode) {
this.postcode = postcode;
}
public Postcode getPostcode() {
return postcode;
}
}
static class Postcode {
@JsonValue
private final String value;
Postcode(String value) {
this.value = value;
}
}
Upvotes: 1