spring-boot json root name

Gre*_*egg 4 json spring-boot

我正在使用spring-boot 1.3.3并试图弄清楚如何在JSON序列化上拥有根名称.例如,我想......

{ stores: [
  {
    id: 1,
    name: "Store1"
  },
  {
    id: 2,
    name: "Store2"
  }]
}
Run Code Online (Sandbox Code Playgroud)

但相反,我得到了

[
  {
    id: 1,
    name: "Store1"
  },
  {
    id: 2,
    name: "Store2"
  }
]
Run Code Online (Sandbox Code Playgroud)

我一直在寻找@JsonRootName和定制Jackson2ObjectMapperBuilder配置但无济于事.在Grails中,这对于Json Views来说非常简单,我也试图看看它是如何直接转换为spring-boot但仍然无法弄明白.

我意识到这与这个问题类似,但我觉得在Spring(boot)的上下文中,它可能会以不同的方式应用,并且想知道如何.

Pas*_*cal 11

解决方案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;
    }
}
Run Code Online (Sandbox Code Playgroud)

参考:Spring文档 - 自定义Jackson ObjectMapper

将@JsonRootElement添加到您的响应实体

@JsonRootName(value = "lot")
public class LotDTO { ... }
Run Code Online (Sandbox Code Playgroud)

HTTP-GET / lot/1的Json结果

{
  "lot": {
    "id": 1,
    "attributes": "...",
    }
}
Run Code Online (Sandbox Code Playgroud)

至少这适用于一个对象的响应.

我还没想出如何自定义集合中的根名称.@Perceptions的回答可能有助于如何使用Jackson重命名JSON序列化中的根密钥


编辑

解决方案2:没有Jackson配置

因为我无法弄清楚如何使用jackson自定义集合中的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
}
Run Code Online (Sandbox Code Playgroud)

向DTO添加注释

@CustomJsonRootName(plural = "articles", singular = "article")
public class ArticleDTO { // Attributes, Getter and Setter }
Run Code Online (Sandbox Code Playgroud)

在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);
 }
Run Code Online (Sandbox Code Playgroud)


小智 7

Spring Boot使用jackson作为json工具,因此可以很好地工作

@JsonTypeName("stores")                                                                                         
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME)
public class stores{ 
.
.
.
 }
Run Code Online (Sandbox Code Playgroud)

  • 这是迄今为止最好的,它更短并且非常灵活,谢谢! (2认同)