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
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:
resWrapper accepts ... of embeddedRes calls.resWrapper.embeddedRes is Object, so you may also supply an instance of ResourceSupportResource. 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"
},...
]
}
}