我试图在Gson输出中使用自定义日期格式,但.setDateFormat(DateFormat.FULL)似乎不起作用,.registerTypeAdapter(Date.class, new DateSerializer())也一样.

就像Gson不在乎对象"日期"并以它的方式打印它.

我该怎么改变呢?

谢谢

编辑:

@Entity
public class AdviceSheet {
  public Date lastModif;
[...]
}

public void method {
   Gson gson = new GsonBuilder().setDateFormat(DateFormat.LONG).create();
   System.out.println(gson.toJson(adviceSheet);
}

我总是用java.util.DatesetDateFormat()不起作用:(

推荐答案

似乎需要定义日期和时间部分的格式,或者使用基于字符串的格式.例如:

Gson gson = new GsonBuilder()
   .setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();

还是using java.text.DateFormat

Gson gson = new GsonBuilder()
   .setDateFormat(DateFormat.FULL, DateFormat.FULL).create();

或者使用序列化程序执行此操作:

我相信格式化程序不能生成时间戳,但这个序列化器/反序列化器对似乎可以工作

JsonSerializer<Date> ser = new JsonSerializer<Date>() {
  @Override
  public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext 
             context) {
    return src == null ? null : new JsonPrimitive(src.getTime());
  }
};

JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
  @Override
  public Date deserialize(JsonElement json, Type typeOfT,
       JsonDeserializationContext context) throws JsonParseException {
    return json == null ? null : new Date(json.getAsLong());
  }
};

Gson gson = new GsonBuilder()
   .registerTypeAdapter(Date.class, ser)
   .registerTypeAdapter(Date.class, deser).create();

如果使用Java 8或更高版本,则应使用上述序列化程序/反序列化程序,如下所示:

JsonSerializer<Date> ser = (src, typeOfSrc, context) -> src == null ? null
            : new JsonPrimitive(src.getTime());

JsonDeserializer<Date> deser = (jSon, typeOfT, context) -> jSon == null ? null : new Date(jSon.getAsLong());

Java相关问答推荐

有没有方法可以修复错误错误:无法初始化主类code_editor?

在FML中删除关键帧动画

如果给定层次 struct 级别,如何从其预序穿越构造n元树

Java 21虚拟线程会解决转向react 式单线程框架的主要原因吗?

如何在Android上获取来电信息

Spring boot:Bean和动态扩展器

最小拓Flutter 排序的时间复杂度是多少?

Jooq外键关系

springboot start loge change

使用GridBagLayout正确渲染

自定义批注的外推属性值

未找到适用于响应类型[类java.io.InputStream]和内容类型[Text/CSV]的HttpMessageConverter

从Spring6中的JPMS模块读取类时出现问题

try 使用预准备语句占位符获取信息时出现Try-With-Resources错误

在Spring Boot JPA for MySQL中为我的所有类创建Bean时出错?

如何在SWT菜单项文本中保留@字符

在缺少字段时使用Jackson With Options生成Optional.Empty()

JavaFX,GridPane:在GridPane的列中生成元素将保持所有列的宽度

简化每个元素本身都是 map 列表的列表

MapStruct记录到记录的映射不起作用