You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Java ZonedDateTime自定义序列化格式(fabric8 Maven插件)

解决方法

方法1:通过插件配置自定义日期格式注解

在Maven pom.xml中,针对java-generator-maven-plugin添加自定义注解配置,覆盖date-time类型默认的JsonFormat参数:

<plugin>
  <groupId>io.fabric8</groupId>
  <artifactId>java-generator-maven-plugin</artifactId>
  <version>6.2.0</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <!-- 保留原有其他配置 -->
        <customAnnotations>
          <customAnnotation>
            <property>date-time</property>
            <annotation>
              @com.fasterxml.jackson.annotation.JsonFormat(timezone = "UTC", pattern = "yyyy-MM-dd'T'HH:mm:ssXXX")
            </annotation>
          </customAnnotation>
        </customAnnotations>
      </configuration>
    </execution>
  </executions>
</plugin>

该配置会直接替换默认生成的JsonFormat注解,生成你需要的时间格式pattern。

方法2:升级插件版本并使用类型映射配置

若可升级到6.4.0及以上版本,插件提供了更清晰的类型映射配置,可精准控制date-time类型的注解:

<plugin>
  <groupId>io.fabric8</groupId>
  <artifactId>java-generator-maven-plugin</artifactId>
  <version>6.4.0</version>
  <executions>
    <execution>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <!-- 保留原有其他配置 -->
        <typeMappings>
          <typeMapping>
            <from>date-time</from>
            <to>java.time.ZonedDateTime</to>
            <annotations>
              <annotation>@com.fasterxml.jackson.annotation.JsonFormat(timezone = "UTC", pattern = "yyyy-MM-dd'T'HH:mm:ssXXX")</annotation>
            </annotations>
          </typeMapping>
        </typeMappings>
      </configuration>
    </execution>
  </executions>
</plugin>

高版本的类型映射配置逻辑更直观,便于后续维护和扩展。

方法3:自定义Mustache模板(兜底方案)

如果上述配置不生效,可通过自定义模板实现:

  1. 复制插件默认的field.mustache模板到项目src/main/resources/templates目录
  2. 修改模板中处理date-time类型的注解代码段,替换为目标pattern
  3. 在插件配置中指定自定义模板路径:
<configuration>
  <!-- 保留原有其他配置 -->
  <templateDirectory>src/main/resources/templates</templateDirectory>
</configuration>

内容的提问来源于stack exchange,提问作者xerocool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 17:22:11