in the RESTController of a Spring Boot Application I retrieve a requestBody as JSON which looks like this:
{id=-1, name=test, street=test, houseNumber=1, postalCode=66111, city=Saarbrücken, sleepingSpots=2, unavailableDates=[2022-06-29 00:00:00.000, 2022-06-30 00:00:00.000]}
I want to create a couch object with the values from this json string, so I try to call constructor and pass the values like this:
new Couch(requestBody.get("name"),..., Integer.parseInt(requestBody.get("postalCode")), ...)
So far, it works fine.
Trouble begins with unavailableDates. Class Couch has attribute:
List<LocalDate> unavailabeDates;
So I try to create a LocalDate object for each date which is inside unavailabeDate part of the json request.
Can you help me to do so?
The string you showed is not JSON. JSON would look like:
{
"id"=-1, "name"="test"
}
For example - quotes around strings. I'm guessing you are getting real JSON, throwing it through a crappy JSON parsing library you should not be using (such as org.json
) that turned it into a Map<String, Object>
, and you then called .toString()
on that.
So, immediate step 1: Search the web for a tutorial on Jackson or GSON, these are JSON parsing libraries you want to use. These 'unmarshall' JSON into a class you make, so, you make a java class that looks like this data, i.e.:
class WhateverThisIs {
int id;
String name;
List<LocalDate> unavailableDates;
}
and in many ways your problem is already solved.
There is a slight weirdness going on here - whatever is making this data is confused about date handling. That's more or less normal, virtually all programming languages are rather fundamentally broken. Java, fortunately, isn't, since Java8 and the introduction of the java.time
package (java.util.Date
, and java.util.Calendar
are worthless, don't use those).
At any rate, having 00:00:00
in a date string that is not supposed to represent time in the first place is problematic, a JSON unmarshaller will probably not silently just assume that those zeroes can be ignored. You can trivially make your own code that turns those strings into a LocalDate, and you can strip the dates off.
If you really, really do not want to use unmarshalling JSON libraries for some crazy reason, note that your input is most likely a List<String>
then, with the list always having 2 dates (the start and the end one). You can turn a string into a LocalDate (the right datatype for what this data is representing) as follows:
private static final DateTimeFormatter MY_DATE_FORMAT = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
public LocalDate String parse(String in) {
var ldt = LocalDateTime.parse(in, MY_DATE_FORMAT);
return ldt.toLocalDate();
}
// example:
parse("2022-06-29 00:00:00.000");
You can use the same code if you're writing custom unmarshalling code to turn that string into the requisite LocalDate
.