I'm developing a simple REST Controller. I'm receiving a SimpleDateFormat object in Request body. Looks like that:
2014-04-13T03:42:06-02:00
My current method now is:
#PostMapping
public ResponseEntity<Flight> addFlight(#RequestBody JSONObject object) {
Flight newFlight = new Flight(object.get("flightNumber").toString(), new
SimpleDateFormat ( object.get("departureDate").toString()));
repository.save(newFlight);
return ResponseEntity.status(HttpStatus.ACCEPTED).body(newFlight);
}
And class
#Data
#Entity
#DynamicUpdate
#NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
#RequiredArgsConstructor
#AllArgsConstructor
public class Flight {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private final String flightNumber;
private final SimpleDateFormat date;
}
Everything is compiling fine, but when I'm sending POST or GET I receive all of the data that I've passed, but SimpleDateFormat is null. How could I repair it?
I've also tried to pass Object to FlightClass and then use a converter in the class's constructor, but I've still had null.
SimpleDateFormat is a legacy class and i would recommend OffsetDateTime since your input represents ISO-8601 with offset
A date-time with an offset from UTC/Greenwich in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00.
OffsetDateTime dateTime = OffsetDateTime.parse(object.get("departureDate").toString());
Related
I have a POJO as below:
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class CalendarData {
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
// field to contain formatted date as per clients requirement - shud be mirror of "date"
private String formattedDate;
private long date;
private String errorCode;
private String subErrorCode;
}
Downstream service is only sending date field as epoch and i want to have the formattedDate populated in run time in given format.
I can always write a custom function to format the data, but want to understand is there any native jackson way or custom setter to do that.
You're almost doing it right. However having a #JsonFormat-Annotation on a String field does not make to much sense, because if it already is String, there is nothing to convert for Jackson anymore. You can just make both fields of type Date and the #JsonFormat annotation on the formattedDate field will serialize it into the proper JSON String representation, exactly in the format you specified in the pattern. Jackson will by default serialize all java.util.Date Object of an object it needs to serialize into the epoch milliseconds as a regular JSON number. So this would work for you. However, as both fields in the final JSON will refer to the exact same Date object it feels weird to have them both as fields of the CalendarData object. I would suggest you just give CalendarData a single field date and then create a getter method for the formattedDate field. Here is what this could look like. By default Jackson will pick up all getter functions and serialize their returned data into the generated json object.
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class CalendarData {
CalendarData(final Date date) {
this.date = date;
}
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
private Date getFormattedDate(){
return this.date;
};
private Date date;
}
UPDATE
As you updates you question I also want to update my answer. I recommend you the following (analogous to what I already explained above).
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
public class CalendarData {
private Date date;
private String errorCode;
private String subErrorCode;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
// field to contain formatted date as per clients requirement - shud be mirror of "date"
private Date getFormattedDate(){
return this.date;
};
}
Then in my main I tried it out
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
CalendarData data = CalendarData.builder()
.errorCode("23")
.subErrorCode("42")
.date(new Date())
.build();
System.out.println(mapper.writeValueAsString(data));
}
Which perfectly prints out
{
"date": 1676642216673,
"errorCode": "23",
"subErrorCode": "42",
"formattedDate": "17/02/2023 13:56:56"
}
Here is my document:
#Data
#Accessors(chain = true)
#Document("Template_Schema")
public class TemplateSchema {
#Id
private String id;
private ZonedDateTime activeFrom;
private ZonedDateTime activeTo;
}
I want to set a maximum date in activeTO field and save it to mongo using a repository.
I've already tried this:
TemplateSchema schema = new TemplateSchema();
Instant maxInstant = Instant.ofEpochMilli(Long.MAX_VALUE);
schema.setActiveTo(maxInstant.atZone(ZoneOffset.UTC));
templateSchemaRepository.save(schema);
This piece of code saves the data. But the date is invalid.
What is the solution to set a maximum date?
I have the following Java Entity:
public class Round {
private ObjectId _id;
#NotEmpty
#Getter
#Setter
#Accessors(fluent = true)
#JsonProperty("userId")
private String userId;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
#JsonDeserialize(using = LocalDateDeserializer.class)
#JsonSerialize(using = LocalDateSerializer.class)
#Getter
#Setter
#Accessors(fluent = true)
#JsonProperty("date")
private LocalDate date;
//other fields
}
When I do a POST to my Spring Boot REST web app with JSON Body:
{
"userId": "user3",
"date": "20-01-2020"
}
The date is persisted in Mongo as follows:
2020-01-20T00:00:00.000+00:00
How can I get the date to persist as simply:
20-01-2020
It's not Java problem, MongoDB uses Date format similar to JavaScript Date format.
If you want to save just dd-MM-YYYY you may want to change your column type to String.
If it's not possible then you need to rewrite your serializer to return String representation of date (and of course rewrite deserializer to parse that string into LocalDate
I try to use JPA Repository to get data from my database. Here I want get all MyObject between startdate and enddate.
Code
Repository
#GetMapping
List<Tache> getMyObjectsByStartdateAfterAndEnddateBefore(#RequestParam Date startdate,
#RequestParam Date enddate);
Controller
#GetMapping(params = {"startdate", "enddate"})
public ResponseEntity<?> findAllByStartdateAfterAndEnddateBefore(#RequestParam("startdate") String startdate,
#RequestParam("enddate") String enddate) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date start = formatter.parse(startdate);
Date end = formatter.parse(enddate);
return new ResponseEntity<>(this.tacheResource.getMyObjectsByStartdateAfterAndEnddateBefore(start, end), HttpStatus.OK);
}
Entity
#Entity
public class MyObject {
#Id
private String id;
#ColumnDefault("CURDATE()")
private String startdate;
private String enddate;
...
}
GET request example
http://localhost:8082/myobject/?startdate=2019-02-19&enddate=2019-06-01
Error (into Repository)
Expected parameter types : String, String
However, I don't understand why because I defined the method with Date type as parameter. Is it because dates are stored as String into my entity?
Your Entities startdate and enddate data types should be Date too in order to get objects with date parameters
#Entity
public class MyObject {
#Id
private String id;
#ColumnDefault("CURDATE()")
private Date startdate;
private Date enddate;
...
}
It should always be a match between jpa method params and your class fields type. In your case, if MyObject has String fields (startDate and endDate), the jpa method should receive String param.
For your particular example, it seems more natural to have your MyObject class with Date fields instead of String:
#Entity
public class MyObject {
#Id
private String id;
#ColumnDefault("CURDATE()")
private Date startdate;
private Date enddate;
...
}
In this way, you will be able to pass Date objects as params to your JPA method.
I know there are many duplicate questions about the same issue, however, I wasn't able to deserialize given date format into java.util.Date object. The client api I am using returns date fields with 6 digit combined with milliseconds and nanoseconds.
2016-12-08T20:09:05.508883Z
2016-12-08T20:09:05.527Z
Sometimes it includes nano seconds sometimes not. I tried to follow deserialization examples from jackson-databind library itself however couldn't found a workaround. Say this is the example json blob
{
"id": "68e6a28f-ae28-4788-8d4f-5ab4e5e5ae08",
"created_at": "2016-12-08T20:09:05.508883Z",
"done_at": "2016-12-08T20:09:05.527Z"
}
Entity.java
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public class OrderResponse {
private String id;
#JsonProperty("created_at")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'*'", timezone = "UTC")
private Date createdAt;
#JsonProperty("done_at")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss'*'", timezone = "UTC")
private Date doneAt;
}
If I only use format yyyy-MM-dd'T'HH:mm:ss jackson mapper deserializes with timezone coming from jvm itself. But I need to use UTC format and I tried also implementing custom deserializer and serializer which doesn't work as well. My question is java.util.Date correct object type? Additionally, I also tried to create my own object mapper with registering new JavaTimeModule() but it didn't work.
Thanks for help.
I found that java.time.format.DateTimeFormatter has ISO_INSTANT format type which supports the format I was looking for.
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT
Basically, I wrote my custom deserializer
public class CustomInstantDeserializer extends JsonDeserializer<Instant> {
private DateTimeFormatter fmt = DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC);
#Override
public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return Instant.from(fmt.parse(p.getText()));
}
}
with #JsonDeserialize annotation on related field.
#JsonProperty("created_at")
#JsonDeserialize(using = CustomInstantDeserializer.class)
private Instant createdAt;