spring MVC 在 spring-数据页面上使用@JsonView
spring MVC use @JsonView on spring-data Page
我在 Jhipster 项目中使用 Spring-MVC、Spring-data-jpa、jackson。
我设法在一个对象上使用了 @JsonView
注释,并且当 rest 控制器中的方法 return 类型 ResponseEntity<List<MyObject>>
时效果很好,但我无法让它工作当方法 return 类型为 ResponseEntity<Page<MyObject>>
.
我尝试将 MapperFeature.DEFAULT_VIEW_INCLUSION
设置为 true(默认为 false)。当我这样做时,所有属性都被序列化。但是通过 @JsonView
过滤不再起作用。
我无法修改 Page
对象,因为它是一个 Spring 数据对象。
我正在寻找一种方法来告诉杰克逊包含 Page
对象的所有属性。
这是我的代码:
我的实体:
@Entity
@Table(name = "T_REGION")
public class Region implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "code", nullable = false)
private Integer code;
@Column(name = "name", length = 60, nullable = false)
@JsonView(View.Summary.class)
private String name;
// Getters and setters
}
我的休息控制器:
@RestController
@RequestMapping("/api")
public class RegionResource {
@RequestMapping(value = "/regionsearch1",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@JsonView(View.Summary.class)
public ResponseEntity<Page<Region>> findAll1(
@RequestParam(value = "page" , required = false) Integer offset,
@RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch1", pageRequest);
return new ResponseEntity<>(page, headers, HttpStatus.OK);
}
@RequestMapping(value = "/regionsearch2",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@JsonView(View.Summary.class)
public ResponseEntity<List<Region>> findAll2(
@RequestParam(value = "page" , required = false) Integer offset,
@RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch2", pageRequest);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
}
findAll1
returns:
[
{
"name": "Ile-de-France"
},
{
"name": "Champagne-Ardenne"
},
....
]
findAll2
returns:
{}
对象 Page
在其属性上没有 @JsonView
因此没有属性被序列化。
即使使用 @JsonView
,我也找不到告诉 Jackson 包含所有 Page
属性的方法。
有什么想法吗?
我遇到了同样的问题,我通过将 MapperFeature.DEFAULT_VIEW_INCLUSION
设置为 true 来解决它,但是您应该在 类 中注释 所有字段 想要应用带有 JsonView
或 JsonIgnore
注释的视图,这样它们就不会默认包含在 json.
中
另一种 return 所有页面元素的方法是为页面接口创建您自己的实现(包括您想要的 JsonView):
JsonPage
public class JsonPage<T> extends org.springframework.data.domain.PageImpl<T> {
public JsonPage(final List<T> content, final Pageable pageable, final long total) {
super(content, pageable, total);
}
public JsonPage(final List<T> content) {
super(content);
}
public JsonPage(final Page<T> page, final Pageable pageable) {
super(page.getContent(), pageable, page.getTotalElements());
}
@JsonView(JsonViews.UiView.class)
public int getTotalPages() {
return super.getTotalPages();
}
@JsonView(JsonViews.UiView.class)
public long getTotalElements() {
return super.getTotalElements();
}
@JsonView(JsonViews.UiView.class)
public boolean hasNext() {
return super.hasNext();
}
@JsonView(JsonViews.UiView.class)
public boolean isLast() {
return super.isLast();
}
@JsonView(JsonViews.UiView.class)
public boolean hasContent() {
return super.hasContent();
}
@JsonView(JsonViews.UiView.class)
public List<T> getContent() {
return super.getContent();
}
}
接下来return这个class到控制器层:
服务
@Override
public Page<User> findAll(final int page) {
PageRequest pr = new PageRequest(page, pageSize, new Sort(Sort.Direction.DESC, "dateCreated"));
return new JsonPage<User>(userRepository.findAll(pr), pr);
}
控制器
@JsonView(JsonViews.UiView.class)
@RequestMapping(method = RequestMethod.GET, value = "{page}")
public Page<User> getUsers(@PathVariable final int page) {
return userService.findAll(page);
}
我这样做过,效果不错
package com.natixis.spring.ws.configuration;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
@Configuration
public class JacksonAdapter extends WebMvcConfigurerAdapter {
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder()
.failOnUnknownProperties(false)
.serializationInclusion(Include.NON_EMPTY)
.serializerByType(Page.class, new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page<?>>{
@Override
public void serialize(Page<?> page, JsonGenerator jsonGen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
ObjectMapper om = new ObjectMapper()
.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.setSerializationInclusion(Include.NON_EMPTY);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(om.writerWithView(serializerProvider.getActiveView())
.writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}
此致,
利马雷吉斯
我知道这是一个老问题,但您可以将类似的内容用于对象页面
@Configuration
public class JacksonAdapter implements WebMvcConfigurer {
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder().failOnUnknownProperties(false).serializerByType(Page.class,
new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page> {
@Override
public void serialize(Page page, JsonGenerator jsonGen, SerializerProvider serializerProvider)
throws IOException {
ObjectMapper om = new ObjectMapper().disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(
om.writerWithView(serializerProvider.getActiveView()).writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}
我在 Jhipster 项目中使用 Spring-MVC、Spring-data-jpa、jackson。
我设法在一个对象上使用了 @JsonView
注释,并且当 rest 控制器中的方法 return 类型 ResponseEntity<List<MyObject>>
时效果很好,但我无法让它工作当方法 return 类型为 ResponseEntity<Page<MyObject>>
.
我尝试将 MapperFeature.DEFAULT_VIEW_INCLUSION
设置为 true(默认为 false)。当我这样做时,所有属性都被序列化。但是通过 @JsonView
过滤不再起作用。
我无法修改 Page
对象,因为它是一个 Spring 数据对象。
我正在寻找一种方法来告诉杰克逊包含 Page
对象的所有属性。
这是我的代码:
我的实体:
@Entity
@Table(name = "T_REGION")
public class Region implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "code", nullable = false)
private Integer code;
@Column(name = "name", length = 60, nullable = false)
@JsonView(View.Summary.class)
private String name;
// Getters and setters
}
我的休息控制器:
@RestController
@RequestMapping("/api")
public class RegionResource {
@RequestMapping(value = "/regionsearch1",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@JsonView(View.Summary.class)
public ResponseEntity<Page<Region>> findAll1(
@RequestParam(value = "page" , required = false) Integer offset,
@RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch1", pageRequest);
return new ResponseEntity<>(page, headers, HttpStatus.OK);
}
@RequestMapping(value = "/regionsearch2",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@JsonView(View.Summary.class)
public ResponseEntity<List<Region>> findAll2(
@RequestParam(value = "page" , required = false) Integer offset,
@RequestParam(value = "per_page", required = false) Integer limit,
Sort sort)
throws URISyntaxException {
Pageable pageRequest = PaginationUtil.generatePageRequest(offset, limit, sort);
Page<Region> page = regionRepository.findAll(pageRequest);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/regionsearch2", pageRequest);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
}
findAll1
returns:
[
{
"name": "Ile-de-France"
},
{
"name": "Champagne-Ardenne"
},
....
]
findAll2
returns:
{}
对象 Page
在其属性上没有 @JsonView
因此没有属性被序列化。
即使使用 @JsonView
,我也找不到告诉 Jackson 包含所有 Page
属性的方法。
有什么想法吗?
我遇到了同样的问题,我通过将 MapperFeature.DEFAULT_VIEW_INCLUSION
设置为 true 来解决它,但是您应该在 类 中注释 所有字段 想要应用带有 JsonView
或 JsonIgnore
注释的视图,这样它们就不会默认包含在 json.
另一种 return 所有页面元素的方法是为页面接口创建您自己的实现(包括您想要的 JsonView):
JsonPage
public class JsonPage<T> extends org.springframework.data.domain.PageImpl<T> {
public JsonPage(final List<T> content, final Pageable pageable, final long total) {
super(content, pageable, total);
}
public JsonPage(final List<T> content) {
super(content);
}
public JsonPage(final Page<T> page, final Pageable pageable) {
super(page.getContent(), pageable, page.getTotalElements());
}
@JsonView(JsonViews.UiView.class)
public int getTotalPages() {
return super.getTotalPages();
}
@JsonView(JsonViews.UiView.class)
public long getTotalElements() {
return super.getTotalElements();
}
@JsonView(JsonViews.UiView.class)
public boolean hasNext() {
return super.hasNext();
}
@JsonView(JsonViews.UiView.class)
public boolean isLast() {
return super.isLast();
}
@JsonView(JsonViews.UiView.class)
public boolean hasContent() {
return super.hasContent();
}
@JsonView(JsonViews.UiView.class)
public List<T> getContent() {
return super.getContent();
}
}
接下来return这个class到控制器层:
服务
@Override
public Page<User> findAll(final int page) {
PageRequest pr = new PageRequest(page, pageSize, new Sort(Sort.Direction.DESC, "dateCreated"));
return new JsonPage<User>(userRepository.findAll(pr), pr);
}
控制器
@JsonView(JsonViews.UiView.class)
@RequestMapping(method = RequestMethod.GET, value = "{page}")
public Page<User> getUsers(@PathVariable final int page) {
return userService.findAll(page);
}
我这样做过,效果不错
package com.natixis.spring.ws.configuration;
import java.io.IOException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Page;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
@Configuration
public class JacksonAdapter extends WebMvcConfigurerAdapter {
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder()
.failOnUnknownProperties(false)
.serializationInclusion(Include.NON_EMPTY)
.serializerByType(Page.class, new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page<?>>{
@Override
public void serialize(Page<?> page, JsonGenerator jsonGen, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
ObjectMapper om = new ObjectMapper()
.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.setSerializationInclusion(Include.NON_EMPTY);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(om.writerWithView(serializerProvider.getActiveView())
.writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}
此致,
利马雷吉斯
我知道这是一个老问题,但您可以将类似的内容用于对象页面
@Configuration
public class JacksonAdapter implements WebMvcConfigurer {
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
return new Jackson2ObjectMapperBuilder().failOnUnknownProperties(false).serializerByType(Page.class,
new JsonPageSerializer());
}
public class JsonPageSerializer extends JsonSerializer<Page> {
@Override
public void serialize(Page page, JsonGenerator jsonGen, SerializerProvider serializerProvider)
throws IOException {
ObjectMapper om = new ObjectMapper().disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
jsonGen.writeStartObject();
jsonGen.writeFieldName("size");
jsonGen.writeNumber(page.getSize());
jsonGen.writeFieldName("number");
jsonGen.writeNumber(page.getNumber());
jsonGen.writeFieldName("totalElements");
jsonGen.writeNumber(page.getTotalElements());
jsonGen.writeFieldName("last");
jsonGen.writeBoolean(page.isLast());
jsonGen.writeFieldName("totalPages");
jsonGen.writeNumber(page.getTotalPages());
jsonGen.writeObjectField("sort", page.getSort());
jsonGen.writeFieldName("first");
jsonGen.writeBoolean(page.isFirst());
jsonGen.writeFieldName("numberOfElements");
jsonGen.writeNumber(page.getNumberOfElements());
jsonGen.writeFieldName("content");
jsonGen.writeRawValue(
om.writerWithView(serializerProvider.getActiveView()).writeValueAsString(page.getContent()));
jsonGen.writeEndObject();
}
}
}