【问题标题】:Spring-data-rest switch between hal+json and plain jsonspring-data-rest 在 hal+json 和 plain json 之间切换
【发布时间】:2017-01-16 14:36:18
【问题描述】:

我一直在使用设置为“application/json”的defaultMediaType 配置属性来获取“普通”JSON,这更容易处理,而且我只需要:

{
    "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
    }
}

但在集成测试中它原来是 impossible to use(不能用 TestRestTemplate 解组,也不能用 Traverson 等解组)。

使用 hal+json 可以很好地与Traverson API 配合使用。

现在,由于名称是 defaultMediaType 并且 Spring Data Rest Reference 总是提到“支持的媒体类型”,我希望使用“Accept”标头在两个变体之间切换。但这不起作用(也尝试了“Content-Type”和两者。使用“application/json 和 application/hal+json”)。

似乎还有一个属性“useHalAsDefaultJsonMediaType”,但据我所知,它根本没有做任何事情。

那么所有的希望都落空了吗?为什么文档如此混乱?有一种在表示之间切换的方法,它的行为不像名称所暗示的那样。没有记录的方法可以反序列化“旧”表示,并且新的表示不能与 TestRestTemplate 一起使用。非常非常令人沮丧。我已经在这上面花了很多时间:(

【问题讨论】:

    标签: java spring rest spring-data spring-data-rest


    【解决方案1】:

    制作一个 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);
        }
    }
    

    设置

    spring.hateoas.use-hal-as-default-json-media-type=false
    

    【讨论】:

      猜你喜欢
      • 2016-10-24
      • 2014-05-05
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      相关资源
      最近更新 更多