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

折月煮酒 提交于 2019-12-23 14:19:15

问题


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:


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


来源:https://stackoverflow.com/questions/41678786/spring-data-rest-switch-between-haljson-and-plain-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!