项目中都会使用 Result 作为接口返回值,分页查询接口中会使用 Result<PageInfo<T>>,T 是实际的返回对象,现在我想使用 @JsonView,发现返回值直接变为空了。我尝试在 ObjectMapper 中增加 Result 的 Serializer 确实可以满足我的要求。但是感觉不太优化,所有接口返回值都是 Result ,影响太大.
下面是我的代码片段
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Result.class, new ResultJsonSerializer(objectMapper));
objectMapper.registerModule(simpleModule);
return objectMapper;
}
@Override
public void serialize(Result<T> page, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
gen.writeStartObject();
gen.writeStringField("code", page.getCode());
gen.writeStringField("msg", page.getMsg());
gen.writeStringField("timestamp", page.getTimestamp());
gen.writeStringField("requestId", page.getRequestId());
gen.writeFieldName("data"); // 将 "data" 字段名称写入
if (page.getData() instanceof PageInfo) {
gen.writeStartObject(); // 开始 JSON 对象
gen.writeBooleanField("isFirstPage", ((PageInfo<?>) page.getData()).isIsFirstPage());
gen.writeBooleanField("hasNextPage", ((PageInfo<?>) page.getData()).isHasNextPage());
gen.writeBooleanField("isLastPage", ((PageInfo<?>) page.getData()).isIsLastPage());
gen.writeBooleanField("hasPreviousPage", ((PageInfo<?>) page.getData()).isHasPreviousPage());
gen.writeNumberField("pages", ((PageInfo<?>) page.getData()).getPages());
gen.writeNumberField("nextPage", ((PageInfo<?>) page.getData()).getNextPage());
gen.writeNumberField("navigatePages", ((PageInfo<?>) page.getData()).getNavigatePages());
gen.writeNumberField("pageNum", ((PageInfo<?>) page.getData()).getPageNum());
gen.writeNumberField("pageSize", ((PageInfo<?>) page.getData()).getPageSize());
gen.writeNumberField("size", ((PageInfo<?>) page.getData()).getSize());
gen.writeNumberField("prePage", ((PageInfo<?>) page.getData()).getPrePage());
gen.writeNumberField("navigateFirstPage", ((PageInfo<?>) page.getData()).getNavigateFirstPage());
gen.writeNumberField("navigateLastPage", ((PageInfo<?>) page.getData()).getNavigateLastPage());
gen.writeNumberField("startRow", ((PageInfo<?>) page.getData()).getStartRow());
gen.writeNumberField("endRow", ((PageInfo<?>) page.getData()).getEndRow());
gen.writeNumberField("total", ((PageInfo<?>) page.getData()).getTotal());
gen.writeArrayFieldStart("list");
objectMapper.writerWithView(serializerProvider.getActiveView()).writeValue(gen, ((PageInfo<?>) page.getData()).getList());
gen.writeEndArray();
gen.writeEndObject(); // 结束 JSON 对象
}else {
objectMapper.writerWithView(serializerProvider.getActiveView()).writeValue(gen, page.getData());
}
gen.writeEndObject();
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.