我正在使用 spring-boot 1.3.3 并试图弄清楚如何在 JSON 序列化中使用根名称。例如,我想...
{ stores: [
{
id: 1,
name: "Store1"
},
{
id: 2,
name: "Store2"
}]
}
但相反我得到
[
{
id: 1,
name: "Store1"
},
{
id: 2,
name: "Store2"
}
]
我一直在看
@JsonRootName
并定制 Jackson2ObjectMapperBuilder
配置但无济于事。在 grails 中,这对于 Json Views 来说非常简单,我也试图看看它是如何直接转换为 spring-boot 但似乎仍然无法弄清楚的。我意识到这类似于 this问题,但我觉得在 Spring (boot) 的上下文中,它可能会有不同的应用,并且想知道如何应用。
最佳答案
解决方案 1:Jackson JsonRootName
I've been looking at
@JsonRootName
andcustomizing the
Jackson2ObjectMapperBuilder
config but to no avail
您对
@JsonRootName
的错误是什么?和 Jackson2ObjectMapperBuilder
?这适用于我的 Spring Boot (1.3.3) 实现:
Jackson 配置 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 配置
Since I couldn't figure out how to customize the json root name in a collection with Kackson
I adapted the answer from @Vaibhav (see 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);
}
关于json - spring-boot json 根名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36746223/