@TOC
JSON.toJSONString(xxx) @JsonFormat失效
问题复现:
引用的依赖
<properties><fastjson.version>1.2.44</fastjson.version>
</properties><dependencies> <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>${fastjson.version}</version></dependency>
</dependencies>
实体类代码:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;@Data
@Accessors(chain = true)
public class SyncDataReq {/*** 数据时间-开始*/// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private LocalDateTime occurrenceTimeBegin;/*** 数据时间-开始*/// @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")private LocalDateTime occurrenceTimeEnd;}
测试代码
@Test
public void test03() {LocalDateTime now = LocalDateTime.now();SyncDataReq req = new SyncDataReq();req.setOccurrenceTimeBegin(now);// @JsonFormat 序列化失效req.setOccurrenceTimeEnd(LocalDateTime.of(2025, 4, 12, 10, 11, 12));//正常格式序列化System.out.println("req = " + JSON.toJSONString(req));
}
测试输出:
req = {"occurrenceTimeBegin":1743410373978,"occurrenceTimeEnd":"2025-04-12 10:11:12"}
问题解决:
fastjson升级到2.0.49版本后,问题解决