W dniu poniedziałek, 10 września 2018 23:36:43 UTC+2 użytkownik Tatu Saloranta napisał: > > On Mon, Sep 10, 2018 at 8:13 AM Slawek Mazur <[email protected] > <javascript:>> wrote: > > > > Here's the scenario: > > > > 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 results in: {"value":"45678"} what I would expect is to see it as > {"postcode":"45678"} > > `@JsonUnwrapped` "peels off" surrounding property, and then all > properties within `Postcode` are > serialized with settings they have. So `@JsonProperty` is ignored, and > that is as designed from > Jackson perspective. > > But to achieve result you want, you would be better off using > `@JsonValue` on `Postcode`: > > static class Postcode { > private final String value; > > // optional: to deserialize from String value > @JsonCreator(mode = JsonCreator.Mode.DELEGATING) > Postcode(String value) { > this.value = value; > } > > @JsonValue > public String getValue() { > return value; > } > } > > in which `Postcode` is serialized as String (and deserialized from > one); you can then still rename > (or not) property that points to it as you wish. > > I hope this helps, > > -+ Tatu +- >
Yes! That's it. That did the job. It's nice coincidence that for Value Objects Jackson has @JsonValue. Thank you. -- You received this message because you are subscribed to the Google Groups "jackson-user" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. For more options, visit https://groups.google.com/d/optout.
