fastjson2
fastjson2 copied to clipboard
JSON.toJSONString() LocalDateTime/LocalDate 不支持自定义格式[BUG]
问题描述
简要描述您碰到的问题。 com.alibaba.fastjson2.JSON.toJSONString() 使用此方法正常,@JSONField 有效; com.alibaba.fastjson.JSON.toJSONString() 使用此兼容包方法则不支持自定义格式,@JSONField 无效;
环境信息
请填写以下信息:
- OS信息: [e.g.:mac]
- JDK信息: [e.g.:Openjdk 1.8.0_333]
- 版本信息:[e.g.:Fastjson2 2.0.10]
重现步骤
如何操作可以重现该问题:
public static void main(String[] args) {
AppResp appResp = new AppResp();
appResp.setTimestamp(LocalDateTime.now());
System.out.println(JSON.toJSONString(appResp));
System.out.println(com.alibaba.fastjson2.JSON.toJSONString(appResp));
JSONObject jsonObject = new JSONObject();
jsonObject.put("appResp",appResp);
System.out.println(jsonObject.toJSONString());
}
期待的正确结果
{"appResp":{"timestamp":"2022-08-05 12:19:19"}}
相关日志输出
{"timestamp":1659673159862} {"appResp":{"timestamp":"2022-08-05 12:19:19"}} {"appResp":{"timestamp":"2022-08-05 12:19:19"}}
AppResp 这个类的代码需要提供下
AppResp 这个类的代码需要提供下
@Data
public class AppResp<T> implements Serializable {
@ApiModelProperty(value = "状态编码", example = "200", required = true)
private String status;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "响应时间", example = "2020-06-01 18:18:18", required = true)
private LocalDateTime timestamp;
@ApiModelProperty(value = "状态描述", example = "成功", required = true)
private String message;
@ApiModelProperty(value = "实体内容", example = "true", required = true)
private T body;
public AppResp() {
timestamp = LocalDateTime.now();
this.status = "200";
this.message = "成功";
}
}
@wenshao 升级2.0.11 兼容包测试, 测试代码同上,直接执行的情况下,没有问题,并且格式也已经正常,如果移除掉第一行日志,则会抛出异常, 上个版本 2.0.10 没有此问题!
public static void main(String[] args) {
AppResp appResp = new AppResp();
appResp.setTimestamp(LocalDateTime.now());
// System.out.println(JSON.toJSONString(appResp));
System.out.println(com.alibaba.fastjson2.JSON.toJSONString(appResp));
JSONObject jsonObject = new JSONObject();
jsonObject.put("appResp",appResp);
System.out.println(jsonObject.toJSONString());
}

https://oss.sonatype.org/content/repositories/snapshots/com/alibaba/fastjson/2.0.12-SNAPSHOT/ 问题已修复,请帮忙用2.0.12-SNAPSHOT版本验证,2.0.12版本预计在8月21日前发布
https://oss.sonatype.org/content/repositories/snapshots/com/alibaba/fastjson/2.0.12-SNAPSHOT/ 问题已修复,请帮忙用2.0.12-SNAPSHOT版本验证,2.0.12版本预计在8月21日前发布
经验证,问题已经解决