Spring HATEOAS embedded resource support

前端 未结 8 879
别那么骄傲
别那么骄傲 2020-12-07 14:12

I want to use the HAL format for my REST API to include embedded resources. I\'m using Spring HATEOAS for my APIs and Spring HATEOAS seems to support embedded resources; how

8条回答
  •  一向
    一向 (楼主)
    2020-12-07 14:44

    Combining the answers above I've made a much easier approach:

    return resWrapper(domainObj, embeddedRes(domainObj.getSettings(), "settings"))
    

    This is a custom utility class (see below). Note:

    • Second argument of resWrapper accepts ... of embeddedRes calls.
    • You may create another method that omits the relation String inside resWrapper.
    • First argument of embeddedRes is Object, so you may also supply an instance of ResourceSupport
    • The result of the expression is of the type that extends Resource. So, it will be processed by all Spring Data REST ResourceProcessor>. You may create a collection of them and also wrap around new Resources<>().

    Create the utility class:

    import com.fasterxml.jackson.annotation.JsonUnwrapped;
    import java.util.Arrays;
    import org.springframework.hateoas.Link;
    import org.springframework.hateoas.Resource;
    import org.springframework.hateoas.Resources;
    import org.springframework.hateoas.core.EmbeddedWrapper;
    import org.springframework.hateoas.core.EmbeddedWrappers;
    
    public class ResourceWithEmbeddable extends Resource {
    
        @SuppressWarnings("FieldCanBeLocal")
        @JsonUnwrapped
        private Resources wrappers;
    
        private ResourceWithEmbeddable(final T content, final Iterable wrappers, final Link... links) {
    
            super(content, links);
            this.wrappers = new Resources<>(wrappers);
        }
    
    
        public static  ResourceWithEmbeddable resWrapper(final T content,
                                                               final EmbeddedWrapper... wrappers) {
    
            return new ResourceWithEmbeddable<>(content, Arrays.asList(wrappers));
    
        }
    
        public static EmbeddedWrapper embeddedRes(final Object source, final String rel) {
            return new EmbeddedWrappers(false).wrap(source, rel);
        }
    }
    

    You only need to include import static package.ResourceWithEmbeddable.* to your service class to use it.

    JSON looks like this:

    {
        "myField1": "1field",
        "myField2": "2field",
        "_embedded": {
            "settings": [
                {
                    "settingName": "mySetting",
                    "value": "1337",
                    "description": "umh"
                },
                {
                    "settingName": "other",
                    "value": "1488",
                    "description": "a"
                },...
            ]
        }
    }
    

提交回复
热议问题