Issue with OffsetDateTime deserialization from json request body Spring-Boot REST API - java

I'm having a OffsetDateTime field in my POJO:
#NotBlank(message = "startTime cannot be null or empty; ")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
#JsonSerialize(using = OffsetDateTimeSerializer.class)
private OffsetDateTime startTime;
When I try to give the request body for the API with this offsetTime JSON field, it shows deserialization error:
: Resolved
[org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Cannot deserialize value of type `java.time.OffsetDateTime`
from String "2020-07-21T12:12:23.000+0200":
Failed to deserialize java.time.OffsetDateTime: (java.time.format.DateTimeParseException)
Text '2020-07-21T12:12:23.000+0200' could not be parsed at index 23;
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:
Cannot deserialize value of type `java.time.OffsetDateTime`
from String "2020-07-21T12:12:23.000+0200":
Failed to deserialize java.time.OffsetDateTime: (java.time.format.DateTimeParseException)
Text '2020-07-21T12:12:23.000+0200' could not be parsed at index 23
Is my input correct and how to deserialize this field from JSON?

Related

JSON Java 8 LocalDateTime format using Jackson in Vert.x

I am trying to create json object from LocaLDateTime but for some reason it is creating json like so, look for issueAt and expireAt key
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,"chronology":{"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,"chronology":{"id":"ISO","calendarType":"iso8601"}}}
I want it to be like so
batch: [0,0,29a1bf70-648e-4cb5-aef8-5377cf702875,2021-10-26T12:36:10,2021-10-27T12:36:10] .
My code for creating the 2 dates is below
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));
In the below code is where I get the error when I try to use mapto to add the json object to my class object.
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);
The error I get is
2021-10-27 09:22:31.133+0330 [vert.x-eventloop-thread-1] ERROR com.galiy.main.MainVerticle - Unhandled:
java.lang.IllegalArgumentException: Cannot construct instance of java.time.LocalDateTime (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.galiy.security.refreshToken.RefreshToken["issuedAt"])
at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:4236) ~[jackson-databind-2.11.4.jar:2.11.4]
and my RefreshToken model is like so,
public class RefreshToken {
private Integer id;
private Integer userID;
private Integer deviceID;
private String refreshToken;
private LocalDateTime issuedAt;
private LocalDateTime expiresAt;
I am not familiar with Vert.x. But according to our discussion under the post, I simply add following 2 line of code before mapTo() and got no error.
ObjectMapper objectMapper = DatabindCodec.mapper();
objectMapper.registerModule(new JavaTimeModule());
Console output:
RefreshToken{id=null, userID=0, deviceID=0, refreshToken='9da220ce-bc66-4561-b924-988c7f394f2d', issuedAt=2021-10-27T17:21:28, expiresAt=2021-10-28T17:21:28}
And in my experience, you can also configure ObjectMapper to handle the output format of LocalDateTime as you want while serialization as follows:
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
You will need to annotate your LocalDateTime member as follows:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss")
LocalDateTime myTime
Here is the link to full answer that explains all the details: Spring Data JPA - ZonedDateTime format for json serialization

Trying to pass a date as a path variable on postman however i get error

I am trying to query my database by passing a date param as path variable on postman using a get mapping, however i keep getting this error "I am trying to query my database by passing a date param as path variable on postman using a get mapping, however I keep getting this error
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:
Failed to convert value of type 'java.lang.String' to required type
'java.sql.Date'; nested exception is
org.springframework.core.convert.ConversionFailedException: Failed to
convert from type [java.lang.String] to type
[#org.springframework.web.bind.annotation.PathVariable
#org.springframework.format.annotation.DateTimeFormat java.sql.Date]
for value '2019-07-24 11:50:34.896+01'; nested exception is
org.springframework.core.convert.ConverterNotFoundException: No
converter found capable of converting from type [java.util.Date] to
type [#org.springframework.web.bind.annotation.PathVariable
#org.springframework.format.annotation.DateTimeFormat java.sql.Date]]
I have tried using the #DateTimeFormat as suggested by various people on line but it still isn't working.
#GetMapping("/walletledger/{fromDate}/{toDate}/{currencycode}")
#PreAuthorize("hasAuthority('SUPERADMIN')")
public List < LedgerResponseDTO > fetchWalletLedgers(
#PathVariable("fromDate") #DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date fromDate,
#PathVariable("toDate") #DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date toDate
}
Implementation
#Override
public List < LedgerResponseDTO > fetchWalletLedgers(
Date fromDate,
Date toDate,
CurrencyCode currencyCode,
Pageable pageable) {
List < LedgerResponseDTO > ledgerList = new ArrayList < > ();
ledgerRepository.findByExecutionDateAndExecutionDateAndCurrencyCode(fromDate, toDate, currencyCode).forEach(ledger - > {
#GetMapping(value = "/date/{from}/{to}")
public String DemoDate(#PathVariable(name = "from") #DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date from,
#PathVariable(name = "to") #DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date to)
{
return from.toString() + " "+ to.toString();
}
URL to be called
localhost:8888/date/2019-07-25/2019-07-26
DateTimeFormat.ISO

Cassandra date insert from Java Spring Project

To the type date in cassandra database I would like to insert a value.
I tried with types java.util.Date and com.datastax.driver.core.LocalDate.
Both ways don't work for me.
For LocalDate error:
"JSON parse error: Can not construct instance of com.datastax.driver.core.LocalDate: no String-argument constructor/factory method to deserialize from String value (''); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.datastax.driver.core.LocalDate: no String-argument constructor/factory method to deserialize from String value ('')\n at [Source: java.io.PushbackInputStream#4d549b00; line: 10, column: 25] (through reference chain: com.comarch.programs.dtos.ProgramDto[\"prgStartDate\"])",
Date error:
"Expected 4 byte long for date (8); nested exception is com.datastax.driver.core.exceptions.InvalidQueryException: Expected 4 byte long for date (8)"
You can do the following way:
private Date accessDate;
#Transient
private Date activeDate;
public Date getActiveDate() {
return activeDate;
}
public void setActiveDate(Date activeDate) {
SimpleDateFormat sp1 = new SimpleDateFormat("yyyyy-MM-dd hh:mm:ss+0000");
String strDate = sp1.format(activeDate);
try {
this.activeDate = sp1.parse(strDate);
setAccessDate(new java.sql.Timestamp(this.activeDate.getTime()));
} catch (ParseException e) {
e.printStackTrace();
}
}
Use a transient data to format the date accordingly and set the date using java.sql.Timestamp

Can not construct instance of javax.xml.datatype.XMLGregorianCalendar from String value

I'm trying to take an XML String and deserialize it into an object. I keep getting this exception though:
com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of javax.xml.datatype.XMLGregorianCalendar from String value '22:32:00': not a valid representation (error: Failed to parse Date value '22:32:00': Unparseable date: "22:32:00")
When it gets to this line:
xmlMapper.readValue(xml, clazz);
My XML contains:
<MyXML>
<Event>
<Time>22:32:00</Time>
</Event
</MyXML>
My object class member variable is:
#XmlElement(name = "Time", required = true)
#XmlSchemaType(name = "time")
#JsonProperty("Time")
#JsonFormat(pattern = "HH:mm:ss", timezone = "GMT+0100")
protected XMLGregorianCalendar time;
Is there anything wrong with this configuration that would cause the above exception?

Could not read JSON: Can not construct instance of java.util.Date from String value

I'm using REST SHARP and creating data using c# code
my service is of Java service.
and i'm getting follwing convertion error
when I pass CreatedDate = DateTime.Now
Json
{"id":123,"createdDate":"2015-08-06T12:18:32.8405195+05:30"}
C# RestSharp code
Customer cust = new Customer()
cust.id=123;
cust.createdDate = DateTime.Now;
string jsonObject = JsonConvert.SerializeObject(cust , new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var restClient = new RestClient("http://myurl/");
var restRequest = new RestRequest("rest/", Method.POST);
restRequest.RequestFormat = DataFormat.Json;
restRequest.AddParameter("application/json", jsonObject, ParameterType.RequestBody);
restRequest.AddHeader("Content-Type", "application/json; charset=utf-8");
// execute the request
RestSharp.IRestResponse restResponse = restClient.Execute(restRequest);
Could not read JSON: Can not construct instance of java.util.Date from
String value '2015-08-06T12:13:01.8564244+05:30': not a valid
representation (error: Failed to parse Date value
'2015-08-06T12:13:01.8564244+05:30': Can not parse date
\"2015-08-06T12:13:01.8564244+05:30\": not compatible with any of
standard forms (\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\",
\"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\", \"EEE, dd MMM yyyy HH:mm:ss zzz\",
\"yyyy-MM-dd\"))\n at [Source:
org.apache.catalina.connector.CoyoteInputStream#19198464; line: 1,
column: 69]

Categories

Resources