如何将java对象转换为简单json字符串,而不将LocalDateTime字段转换为扩展json对象?

如何将java对象转换为简单json字符串,而不将LocalDateTime字段转换为扩展json对象?,java,json,spring-boot,gson,Java,Json,Spring Boot,Gson,我需要帮助将java对象转换为json字符串,而无需将LocalDateTime字段转换为单独的对象 class MyObj { LocalDateTime date; } 那么 当我将其转换为json时 Gson gson = new GsonBuilder().setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create(); gson.toJson(dateObj); 我明白了: { "date&quo

我需要帮助将java对象转换为json字符串,而无需将LocalDateTime字段转换为单独的对象

class MyObj {
 LocalDateTime date;
}
那么

当我将其转换为json时

Gson gson = new GsonBuilder().setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
gson.toJson(dateObj);
我明白了:

 {
  "date": {
    "date": {
      "year": 2020,
      "month": 8,
      "day": 27
    },
    "time": {
      "hour": 8,
      "minute": 59,
      "second": 47,
      "nano": 0
    }
  }
}
但我想要这个:

"date" : "2020-08-27T08:59:470Z"
请帮助我。

根据
setDateFormat

日期格式将用于序列化和反序列化{@link java.util.date}、{@link java.sql.Timestamp}和{@link java.sql.date}。 您需要为
LocalDateTime.class

JsonSerializer<LocalDateTime> localDateTimeSerializer = (src, type, context) -> {
    String date = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").format(src);
    // String date = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(src);
    // String date = src.toString();
    return new JsonPrimitive(date);
};

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, localDateTimeSerializer).create();
gson.toJson(dateObj);
JsonSerializer localDateTimeSerializer=(src,type,context)->{
字符串date=DateTimeFormatter.of模式(“yyyy-MM-dd'T'HH:MM:ss”).format(src);
//字符串日期=DateTimeFormatter.ISO\u LOCAL\u date\u TIME.format(src);
//字符串日期=src.toString();
返回新的JsonPrimitive(日期);
};
Gson Gson=new GsonBuilder().registerTypeAdapter(LocalDateTime.class,localDateTimeSerializer).create();
toJson(dateObj);
注意:LocalDateTime不存储时区信息,因此您不能在日期格式模式中实际使用
Z

我用这种方法解决了这个问题

创建Gson对象:

Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
            .create();
使用如下方法:

String jsonRequestString = gson.toJson(request);
创建序列化程序:

class LocalDateAdapter implements JsonSerializer<LocalDate> {

@Override
public JsonElement serialize(LocalDate date, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}
class LocalDateAdapter实现JsonSerializer{
@凌驾
公共JsonElement序列化(LocalDate、java.lang.reflect.Type typeOfSrc、JsonSerializationContext){
返回新的JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_date));
}
}
class LocalDateAdapter implements JsonSerializer<LocalDate> {

@Override
public JsonElement serialize(LocalDate date, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
    return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}