Formatter<LocalDateTime> 在Spring Boot容器中没有注册到REST应用程序中。

huangapple 未分类评论47阅读模式
英文:

Formatter<LocalDateTime> not getting registered with Spring Boot container in REST application

问题

我在一个REST Spring Boot Web服务应用中实现了一个Formatter<LocalDateTime>用于格式化所有LocalDateTimeJava 8属性以便在Web服务响应中以特定格式显示

public class LocalDateTimeFormatter implements Formatter<LocalDateTime> {

    @Override
    public String print(LocalDateTime temporal, Locale locale) {
        DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern("yyyy-MM-dd HH:mm:ss");
        return formatter.format(temporal);
    }

    @Override
    public LocalDateTime parse(String text, Locale locale)
            throws ParseException {
        return LocalDateTime.parse(text);
    }

}

该格式化程序还已在下面的代码中注册以便在应用程序级别上运行以避免单独对所有LocalDateTime属性进行注释

@Configuration
public class ContentFormatter implements WebMvcConfigurer {
   
    @Override
    public void addFormatters(FormatterRegistry registry) {
            registry.addFormatter(new LocalDateTimeFormatter());
    }
}

但是从Web服务的响应中未应用任何格式化accessDate是LocalDateTime类型的属性

{
  "content" : "Hello, World!",
  "id" : 0,
  "accessDate" : "2020-04-07T19:56:41.48"
}
英文:

I have implemented a Formatter<LocalDateTime> in a REST Spring Boot web service application to format all LocalDateTime (Java 8) attributes so that they get displayed in a specific format in the web service response.

public class LocalDateTimeFormatter implements Formatter&lt;LocalDateTime&gt; {

    @Override
    public String print(LocalDateTime temporal, Locale locale) {
        DateTimeFormatter formatter = DateTimeFormatter
                .ofPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;);
        return formatter.format(temporal);
    }

    @Override
    public LocalDateTime parse(String text, Locale locale)
            throws ParseException {
        return LocalDateTime.parse(text);
    }

}

The formatter has also been registered as shown below so that it works at the application level in order to avoid annotating all LocalDateTime attributes individually

@Configuration
public class ContentFormatter implements WebMvcConfigurer {
   
    @Override
    public void addFormatters(FormatterRegistry registry) {
            registry.addFormatter(new LocalDateTimeFormatter());
    }
}

But no formatting is applied to the response from the web service, accessDate being the LocalDateTime type of attribute

{
  &quot;content&quot; : &quot;Hello, World!&quot;,
  &quot;id&quot; : 0,
  &quot;accessDate&quot; : &quot;2020-04-07T19:56:41.48&quot;
 }

答案1

得分: 0

你可能甚至不需要实现你的格式化并注册它。只需按以下方式注释您的LocalDateTime属性:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
public LocalDateTime getTime() {
    return time;
}

此外,您可能需要添加以下依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.6.0</version>
</dependency>

有关详细信息,请参阅此问题及其答案:
Spring Data JPA - ZonedDateTime格式化用于JSON序列化

英文:

You probably don't even need to implement your formatted and register it. Just annotate your LocalDateTime property as follows:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = &quot;yyyy-MM-dd HH:mm:ss&quot;)
public LocalDateTime getTime() {
    return time;
}

Also, you might need to add the following dependency:

&lt;dependency&gt;
    &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;
    &lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;
    &lt;version&gt;2.6.0&lt;/version&gt;
&lt;/dependency&gt;

See this question and its answer for details:
Spring Data JPA - ZonedDateTime format for json serialization

答案2

得分: 0

你可以使用 StdSerializer

public class JacksonLocalDateSerializer extends StdSerializer<LocalDate> {

  private static final long serialVersionUID = -7880057299936771237L;

  private static final DateTimeFormatter formatter =
      DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
      .withResolverStyle(ResolverStyle.STRICT);

  public JacksonLocalDateSerializer() {
    this(null);
  }

  public JacksonLocalDateSerializer(Class<LocalDate> type) {
    super(type);
  }

  @Override
  public void serialize(LocalDate value, JsonGenerator jsonGenerator,
      SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
    jsonGenerator.writeString(formatter.format(value));
  }
}

然后为整个应用程序添加序列化器的配置

@Configuration
public class JacksonConfig {

  @Bean
  @Primary
  public ObjectMapper configureObjectMapper() {

    JavaTimeModule javaTimeModule = new JavaTimeModule();

    javaTimeModule.addSerializer(LocalDateTime.class, new JacksonLocalDateTimeSerializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(javaTimeModule);
    return mapper;
  }

}
英文:

You can use StdSerializer

public class JacksonLocalDateSerializer extends StdSerializer&lt;LocalDate&gt; {

  private static final long serialVersionUID = -7880057299936771237L;

  private static final DateTimeFormatter formatter =
      DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd HH:mm:ss&quot;)
      .withResolverStyle(ResolverStyle.STRICT);

  public JacksonLocalDateSerializer() {
    this(null);
  }

  public JacksonLocalDateSerializer(Class&lt;LocalDate&gt; type) {
    super(type);
  }

  @Override
  public void serialize(LocalDate value, JsonGenerator jsonGenerator,
      SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
    jsonGenerator.writeString(formatter.format(value));
  }
}

Then add configuration for the serializer for applicable the entire application


@Configuration
public class JacksonConfig {

  @Bean
  @Primary
  public ObjectMapper configureObjectMapper() {

    JavaTimeModule javaTimeModule = new JavaTimeModule();

    javaTimeModule.addSerializer(LocalDateTime.class, new JacksonLocalDateTimeSerializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(javaTimeModule);
    return mapper;
  }

}

huangapple
  • 本文由 发表于 2020年4月7日 22:29:11
  • 转载请务必保留本文链接:https://java.coder-hub.com/61082383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定