Spring-data-rest switch between hal+json and plain

2019-06-25 05:14发布

I've been using the defaultMediaType config property set to "application/json" to get "normal" JSON, which is easier to handle and all I need:

{
    "links": [
    ],
    "content": [
        {
            "username": "admin",
            "id": 1,
            "authorities": [
                "ROLE_ADMIN"
            ],
            "content": [ ],
            "links": [
                {
                    "rel": "self",
                    "href": "http://localhost:8080/apiv1/data/users/1"
                },
                {
                    "rel": "logisUser",
                    "href": "http://localhost:8080/apiv1/data/users/1"
                },
                {
                    "rel": "mandant",
                    "href": "http://localhost:8080/apiv1/data/users/1/mandant"
                }
            ]
        },...
    ],
    "page": {
        "size": 20,
        "totalElements": 3,
        "totalPages": 1,
        "number": 0
    }
}

But it turned out to be impossible to use in Integration tests (can't unmarshall with TestRestTemplate, nor with Traverson, etc.).

Using hal+json works nicely with the Traverson API.

Now, since the name is defaultMediaType and the Spring Data Rest Reference always mentions "Supported media types", I expected to switch between the two variants using the "Accept" header. But that doesn't work (also tried "Content-Type" and both. With "application/json and application/hal+json").

There also seems to be a property "useHalAsDefaultJsonMediaType", but that doesn't do anything at all, as far as I can see.

So is all hope lost? And why is the documentation so confusing? There is one way to switch between the representations, which doesn't behave as the name suggests. There's no documented way to deserialize the "old" representation and the new one can't be used with TestRestTemplate. Very, very frustrating. I've spent lots of time on this already :(

1条回答
家丑人穷心不美
2楼-- · 2019-06-25 05:23

Make a RepositoryRestConfigurer

@Configuration
public class RestRepositoryConfig extends RepositoryRestConfigurerAdapter {
    @Value("${spring.hateoas.use-hal-as-default-json-media-type:true}")
    private boolean useHalAsDefaultJsonMediaType;

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
         config.useHalAsDefaultJsonMediaType(useHalAsDefaultJsonMediaType);
    }
}

And set

spring.hateoas.use-hal-as-default-json-media-type=false
查看更多
登录 后发表回答