我正在嘗試從 LocalDateTime 創建 json 物件,但由于某種原因,它正在像這樣創建 json,查找 issueAt 和 expireAt 鍵
json {"userID":0,"deviceID":0,"refreshToken":"93180548-23b3-4d1b-8b5b-a105b7cff7f9", "issuedAt" :{"year":2021,"monthValue":10,"dayOfMonth" :27,"hour":9,"minute":22,"second":31,"nano":0,"month":"OCTOBER","dayOfWeek":"WEDNESDAY","dayOfYear":300,"年表":{"id":"ISO","calendarType":"iso8601"}}, "expiresAt" :{"year":2021,"monthValue":10,"dayOfMonth":28,"hour":9 ,"minute":22,"second":31,"nano":0,"month":"OCTOBER","dayOfWeek":"THURSDAY","dayOfYear":301,"年表":{"id":"ISO","calendarType":"iso8601"}}}
我希望它像這樣
批次:[0,0,29a1bf70-648e-4cb5-aef8-5377cf702875, 2021-10-26T12:36:10,2021-10-27T12:36:10 ]。
我創建 2 個日期的代碼如下
String randomString = UUID.randomUUID().toString();
Instant myInstant1 = Instant.now().truncatedTo(ChronoUnit.SECONDS);
LocalDateTime issuedAt = LocalDateTime.ofInstant(myInstant1, ZoneId.systemDefault());
System.out.println("issued_at : " issuedAt);
LocalDateTime expiresAt = issuedAt.plusDays(1);
System.out.println("expires_at: " expiresAt.plusDays(1));
在下面的代碼中,當我嘗試使用 mapto 將 json 物件添加到我的類物件時出現錯誤。
JsonObject json = new JsonObject()
.put("userID", userID)
.put("deviceID", deviceID)
.put("refreshToken", randomString)
.put("issuedAt", issuedAt)
.put("expiresAt", expiresAt);
LOG.info("json {}", json.encode());
RefreshToken refreshTokenObj = json.mapTo(RefreshToken.class); //here I am trying to mapTo my class and I get the error
LOG.info("refreshTokenObj {}", refreshTokenObj);
我得到的錯誤是
2021 年 10 月 27 日 09:22:31.133 0330 [vert.x-eventloop-thread-1] 錯誤 com.galiy.main.MainVerticle - 未處理:java.lang.IllegalArgumentException:無法構造實體
java.time.LocalDateTime(無創建者,如默認)建構式,存在):無法從 [來源:未知;行:-1,列:-1](通過參考鏈:com.galiy.security.refreshToken.RefreshToken["issuedAt"])在 com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:4236) ~ [jackson-databind-2.11.4.jar:2.11.4]
我的 RefreshToken 模型是這樣的,
public class RefreshToken {
private Integer id;
private Integer userID;
private Integer deviceID;
private String refreshToken;
private LocalDateTime issuedAt;
private LocalDateTime expiresAt;
uj5u.com熱心網友回復:
我不熟悉Vert.x。但是根據我們在帖子下的討論,我之前簡單地添加了以下 2 行代碼,mapTo()并沒有出現錯誤。
ObjectMapper objectMapper = DatabindCodec.mapper();
objectMapper.registerModule(new JavaTimeModule());
控制臺輸出:
RefreshToken{id=null, userID=0, deviceID=0, refreshToken='9da220ce-bc66-4561-b924-988c7f394f2d',issuedAt=2021-10-27T17:21:28, expiresAt=2021-10-21:T17:2 28}
根據我的經驗,您還可以配置ObjectMapper為LocalDateTime在序列化時根據需要處理輸出格式,如下所示:
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
uj5u.com熱心網友回復:
您需要按如下方式注釋 LocalDateTime 成員:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
LocalDateTime myTime
這是解釋所有細節的完整答案的鏈接:Spring Data JPA - ZonedDateTime format for json serialization
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/338283.html
上一篇:用于下載站點上提供的所有pdf的R代碼:Webscrapping
下一篇:從JSON中選擇
