解决方案 1:Jackson JsonRootName
我一直在看@JsonRootName 和
自定义 Jackson2ObjectMapperBuilder 配置但无济于事
@JsonRootName 和 Jackson2ObjectMapperBuilder 有哪些错误?
这适用于我的 Spring Boot (1.3.3) 实现:
杰克逊配置 Bean
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.featuresToEnable(SerializationFeature.WRAP_ROOT_VALUE);
// enables wrapping for root elements
return builder;
}
}
参考:Spring Documentation - Customizing the Jackson ObjectMapper
将@JsonRootElement 添加到您的响应实体
@JsonRootName(value = "lot")
public class LotDTO { ... }
Json 结果 用于 HTTP-GET /lot/1
{
"lot": {
"id": 1,
"attributes": "...",
}
}
至少这适用于一个对象的响应。
我还没有弄清楚如何自定义集合中的根名称。 @Perceptions 的回答可能会有所帮助 How to rename root key in JSON serialization with Jackson
编辑
解决方案 2:没有 Jackson 配置
由于我不知道如何使用 Kackson 自定义集合中的 json 根名称
我改编了@Vaibhav 的答案(见2):
自定义 Java 注释
@Retention(value = RetentionPolicy.RUNTIME)
public @interface CustomJsonRootName {
String singular(); // element root name for a single object
String plural(); // element root name for collections
}
向 DTO 添加注释
@CustomJsonRootName(plural = "articles", singular = "article")
public class ArticleDTO { // Attributes, Getter and Setter }
在 Spring Controller 中返回 Map 作为结果
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Map<String, List<ArticleDTO>>> findAll() {
List<ArticleDTO> articles = articleService.findAll();
if (articles.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Map result = new HashMap();
result.put(ArticleDTO.class.getAnnotation(CustomJsonRootName.class).plural(), articles);
return new ResponseEntity<>(result, HttpStatus.OK);
}