相关疑难解决方法(0)

如何自定义Spring Boot隐式使用的Jackson JSON映射器?

我正在使用Spring Boot(1.2.1),其方式与构建RESTful Web服务教程的方式类似:

@RestController
public class EventController {

    @RequestMapping("/events/all")
    EventList events() {
        return proxyService.getAllEvents();
    }

}
Run Code Online (Sandbox Code Playgroud)

所以上面,Spring MVC暗中使用Jackson将我的EventList对象序列化为JSON.

但我想对JSON格式进行一些简单的自定义,例如:

setSerializationInclusion(JsonInclude.Include.NON_NULL)
Run Code Online (Sandbox Code Playgroud)

问题是,自定义隐式JSON映射器的最简单方法什么?

我在这篇博客文章中尝试了这种方法,创建了一个CustomObjectMapper等等,但是第3步"在Spring上下文中注册类"失败了:

org.springframework.beans.factory.BeanCreationException: 
  Error creating bean with name 'jacksonFix': Injection of autowired dependencies failed; 
  nested exception is org.springframework.beans.factory.BeanCreationException: 
  Could not autowire method: public void com.acme.project.JacksonFix.setAnnotationMethodHandlerAdapter(org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter); 
  nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
  No qualifying bean of type [org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter]   
  found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc jackson spring-boot

89
推荐指数
8
解决办法
13万
查看次数

Java 8 日期时间类型使用 Spring Boot 序列化为对象

我有一个包含 Java 8 日期时间类型字段的实体。问题是这些字段被序列化为对象。我添加了jackson-datatype-jsr310依赖项,因此 Spring Boot 1.5.7 会自动配置JavaTimeModule处理 Java 8 日期时间类型。看来该模块没有注册(我在 JavaTimeModule 构造函数中放置了一个断点)。我知道我不需要定制ObjectMapper。我花了几个小时阅读该问题,解决方案始终是添加jackson-datatype-jsr310依赖项,但它在我的情况下不起作用。

实体:

@Entity
public class DateTimeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private LocalDate localDate;

    private LocalDateTime localDateTime;

    private Instant instant;

    private OffsetDateTime offsetDateTime;

    private ZonedDateTime zonedDateTime;

}
Run Code Online (Sandbox Code Playgroud)

RestController 方法:

@GetMapping("/datetimes/{id}")
public ResponseEntity<DateTimeEntity> getById(@PathVariable Long id) {
    DateTimeEntity dateTimeEntity = dateTimeRepository.findOne(id);
    return new ResponseEntity<DateTimeEntity>(dateTimeEntity, HttpStatus.OK);

}
Run Code Online (Sandbox Code Playgroud)

返回的 JSON 对象:

    {
    "id": 1,
    "localDate": null,
    "localDateTime": null,
    "instant": { …
Run Code Online (Sandbox Code Playgroud)

spring spring-boot

21
推荐指数
4
解决办法
3万
查看次数

标签 统计

spring ×2

spring-boot ×2

jackson ×1

java ×1

spring-mvc ×1