16

此问题出现在 Spring-Data 版本 2 中。在最新版本 1.13.9(及更早版本)中,它运行良好。

控制器代码:

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

    @RequestMapping(value = "sorttest", method = RequestMethod.GET)
    public Page<Integer> getDummy() {
        return new PageImpl<>(Collections.singletonList(1), new PageRequest(0, 5, new Sort("asdf")), 1);
    }

}

Spring-Data 2 风格相同:

Pageable pageable = PageRequest.of(0, 10, new Sort(Sort.Direction.ASC, "asd"));
PageImpl<Integer> page = new PageImpl<Integer>(Lists.newArrayList(1,2,3), pageable, 3);
return page;

配置:

@SpringBootApplication
@EnableWebMvc
@EnableSpringDataWebSupport
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

还尝试了简单的 Spring 应用程序,没有 Spring Boot 和 Java 配置以及 XML 配置。结果是一样的:

{
    "content": [
        1
    ],
    "pageable": {
        "sort": {
            "sorted": true,
            "unsorted": false
        },
        "offset": 0,
        "pageSize": 5,
        "pageNumber": 0,
        "paged": true,
        "unpaged": false
    },
    "totalElements": 1,
    "last": true,
    "totalPages": 1,
    "size": 5,
    "number": 0,
    "sort": {
        "sorted": true,
        "unsorted": false
    },
    "numberOfElements": 1,
    "first": true
}

如果我将 Spring-Data 版本更改为 1.X,我将得到正确的 JSON 响应来排序对象:

{
    "content": [
        1
    ],
    "totalElements": 1,
    "totalPages": 1,
    "last": true,
    "size": 5,
    "number": 0,
    "sort": [
        {
            "direction": "ASC",
            "property": "asdf",
            "ignoreCase": false,
            "nullHandling": "NATIVE",
            "ascending": true,
            "descending": false
        }
    ],
    "numberOfElements": 1,
    "first": true
}

似乎我什么都试过了,我没有在更新日志中找到任何关于排序更改的通知,我在 Spring JIRA 中没有发现这样的问题。

所以问题是我如何使用 spring-data 2.X libs JSON 排序如下:

"sort": [
    {
        "direction": "ASC",
        "property": "asdf",
        "ignoreCase": false,
        "nullHandling": "NATIVE",
        "ascending": true,
        "descending": false
    }
]

代替:

"sort": {
    "sorted": true,
    "unsorted": false
}
4

2 回答 2

9

@Oleg Danyliuk

我遇到了和你一样的问题,发现你的回答很有用,但是在这里我提供了一个最短的答案。


正如您所说,需要为 Sort 类创建一个自定义序列化程序

但是,您只需要注释 JsonSerializer 类即可将其@JsonComponent注册到 Jackson。


解决方案

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.data.domain.Sort;

import java.io.IOException;

@JsonComponent
public class SortJsonSerializer extends JsonSerializer<Sort> {

    @Override
    public void serialize(Sort value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartArray();

        value.iterator().forEachRemaining(v -> {
            try {
                gen.writeObject(v);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        gen.writeEndArray();
    }

    @Override
    public Class<Sort> handledType() {
        return Sort.class;
    }
}

参考

于 2018-03-06T15:41:59.963 回答
4

我已经解决了添加自定义序列化器的问题:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.data.domain.Sort;

import java.io.IOException;

public class SortJsonSerializer extends JsonSerializer<Sort> {

    @Override
    public void serialize(Sort orders, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartArray();
        orders.iterator().forEachRemaining(o -> {
            try {
                jsonGenerator.writeObject(o);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        jsonGenerator.writeEndArray();
    }

    @Override
    public Class<Sort> handledType() {
        return Sort.class;
    }

}

为了让 Spring 使用它,我重写了 extendMessageConverters:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.xxx.ws"})
@EnableSpringDataWebSupport
public class SpringWebConfig implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        SortHandlerMethodArgumentResolver sortResolver = new SortHandlerMethodArgumentResolver();

        // For sorting resolution alone
        argumentResolvers.add(sortResolver);

        PageableHandlerMethodArgumentResolver pageableResolver = new PageableHandlerMethodArgumentResolver(sortResolver);
        pageableResolver.setMaxPageSize(10000);

        // For sorting resolution encapsulated inside a pageable
        argumentResolvers.add(pageableResolver);

        argumentResolvers.add(new CurrentUserArgumentResolver());
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        SimpleModule module = new SimpleModule();
        module.addSerializer(Sort.class, new SortJsonSerializer());
        return new Jackson2ObjectMapperBuilder()
                .findModulesViaServiceLoader(true)
                .modulesToInstall(module);
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //First converters added in WebMvcConfigurationSupport.addDefaultHttpMessageConverters and then we add our behaviour here
        Jackson2ObjectMapperBuilder builder = jackson2ObjectMapperBuilder();

        for (int i=0; i<converters.size(); i++) {
            if (converters.get(i) instanceof MappingJackson2HttpMessageConverter) {
                converters.set(i, new MappingJackson2HttpMessageConverter(builder.build()));
            }
        }
    }
}
于 2018-02-09T08:04:01.367 回答