[英]How to convert a java object to simple json string without converting the LocalDateTime field to an extended json object?
我需要幫助將 java 對象轉換為 json 字符串,而無需將 LocalDateTime 字段轉換為單獨的對象。
class MyObj {
LocalDateTime date;
}
然后,
MyObj dateObj = new MyObj();
dateObj.date = LocalDateTime.now();
當我將其轉換為 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"
請幫我解決這個問題。
我是這樣解決的。
創建一個 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));
}
}
根據setDateFormat
javadoc
日期格式將用於序列化和反序列化 {@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);
注意: LocalDateTime 不存儲時區信息,因此您實際上不能在日期格式模式中使用Z
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.