Search code examples
javaembeddablejpa

Use @Embeddable Without Nested JSON


I'm trying to use the @Embedded and @Embeddable javax annotations to keep my Java classes cleaner, but I want the resulting JSON to be flattened.

THE DESIRED BEHAVIOR:

[
    {
        "id": "6edbced5-2d27-4257-a140-2925291daaf6",
        "name": "Online Maria DB",
        "address": "Syble Forks",
        "city": "Dallas",
        "state": "Texas",
        "country": "United States"
        "phoneNumber": "(789) 740-5789",
        "orgUserName": "online-maria"
    }
]

THE ACTUAL BEHAVIOR:

[
    {
        "id": "6edbced5-2d27-4257-a140-2925291daaf6",
        "name": "Online Maria DB",
        "addressDetails": {
            "address": "Syble Forks",
            "city": "Dallas",
            "state": "Texas",
            "country": "United States"
        },
        "phoneNumber": "(789) 740-5789",
        "orgUserName": "online-maria"
    }
]

Is this possible using these annotation?

What I have so far:

Organization.java

@Embedded
private Address address;

Address.java

@Embeddable
public class Address {
    ...
}


Solution

  • You can use Jackson's @JsonUnwrapped annotation if you do use Jackson. Also you can write custom serializer as well

    public class Organization {
    
        @JsonUnwrapped
        @Embedded
        private Address address;
       
        // other code
    }