Search code examples
javajsonspring-bootrestdto

How to change JSON representation for single value java object?


I had a class like:

public class EmailAddress {
   public String value;

   public String tld() {...}
   public String host() {...}
   public String mailbox() {...}
}

Now I use this class in an Object / Entity:

@Entity
public class Customer {
    public String name;
    public EmailAddress mail;
}

Now, when I do a rest service for Customer, I get this format:

{
    "id": 1,
    "name": "Test",
    "email": {
        "value": "[email protected]"
    }
}

But I only want "email": "[email protected]"

{
    "id": 1,
    "name": "Test",
    "email": "[email protected]"
}

What I must do? I use Spring Boot and Hibernate Entities.

Thank you for any support


Solution

  • I found an other easier solution, use a JsonSerializer on the entity Property:

    @JsonSerialize(using = EmailAddressSerializer.class)
    private EmailAddress email;
    

    The serializer class:

    public class EmailAddressSerializer extends StdSerializer<EmailAddress> {
    
        public EmailAddressSerializer() {
            super(EmailAddress.class);
        }
    
        protected EmailAddressSerializer(Class<EmailAddress> t) {
            super(t);
        }
    
        @Override
        public void serialize(EmailAddress email,
                              JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(email.value);
        }
    }