Calling the service from Android passing LocalDateTime type parameter.I'm getting this expection while casting request parameter which was send as same Type(LocalDateTime) to LocalDateTime.
here is what i'm doing
@PostMapping(value = "/getDates")
public Object getDates(@RequestBody Map<Object, Object> request) {
LocalDateTime startDate = (LocalDateTime) request.get("fromDate");
LocalDateTime endDate = (LocalDateTime) request.get("toDate");
}
API Request
{
"fromDate":LocalDateTimeObject
"toDate":LocalDateTimeObject1
}
The cast operator does 3 different things: Primitive conversion, typecheck, and type assertion.
These 3 things are like guns and grandmas: Utterly, completely, entirely unrelated. They look similar. It ends there.
The only one of those 3 that actually converts things, is primitive conversion. As the name indicates, this one happens if the thing int the parentheses is a primitive type, such as 'int'.
In other words, (LocalDateTime) foo
is typecheck: It checks if foo
is a LocalDateTime. If yes, nothing happens. If no, a ClassCastException
is thrown.
It looks like you expect it to convert the "fromDate"
parameter to a LocalDateTime
- a cast is not how you can accomplish this.
JSON can only represent booleans, numbers, strings, arrays, and maps. It cannot represent date time objects. That means that your API should define how to do this. The usual way is via string, by putting in the spec that datetimes are passed for example as: "2020-05-20 14:00"
. Or possibly as a number: Number of milliseconds since 1970, at UTC, then take the local datetime you find there, and that's what I meant. That is a bit more unwieldy, but it's your API, you get to spec it however you want.
From your error, it looks like you've just tossed a LocalDateTime object at a JSON marshaller, which turned it into a convoluted map structure representing the fields of the LDT object.
This is not workable; I strongly suggest you retool this.
Your first step is to figure out what your spec is. Once you've determined this, your second step is how to convert the string or millis-since-epoch you get into an LDT instance (or if you insist, this map structure).
If it's a string with year-month-day, use java.time.format.DateTimeFormatter
to make the appropriate pattern (check the constants, one probably is good to go here), and use that: LocalDateTime.parse(request.get("fromDate"), DateTimeFormatter.ISO_LOCAL_DATE_TIME)
If you have epoch millis (I don't recommend this), Instant.ofEpochMilli(Long.parseLong(request.get("fromDate"))).atZone(ZoneOffset.UTC).toLocalDateTime()
.
Use the same library (presumably, GSON or jackson) to demarshal the map that you used to marshal it. Whatever the client sent you? They are using one of those two libraries. Use the same and reverse the operation.
I strongly recommend option #1.