From post man (rest service) how to post json date (string format) in java that accepts date object

How to bind dateOfJoining value (string type) to member variable "dateOfJoining" (date type) in class "DateInput" after sending below JSON via postman. How to convert String to Date object in java with the same dd / MM / yyyy format. The converted date must be in a Date object, but not a String.

Json is given below

{
 "dateOfJoining" : "03/04/2017"
}

      

Service url in postman column - localhost / Rest / hello

RestService class in java - HandleRestRequest.java

@RestController
public class HandleRestRequest
{

  @RequestMapping("\hello");
  public List setRequestParams(@RequestBody DateInput dateInput)
 {
   .......
  }
 }

 Pojo Class DateInput.java

  public class DateInput
 {
  private  Date dateOfJoining;
   .......
  }

      

If I send date from json in bottom format its throw error as unsatisfactory input

 {
  "dateOfJoining" : 04/04/2017
 }

      

So i am sending it as string format and changing dateOfJoining as string in DateInput.java file and later i tried to convert it as date object as below

Modified DateInput.java file from date to string

 public class DateInput
 {
  private  String dateOfJoining;
   .......
 }

      

Modified JSON

{
 "dateOfJoining" : "04/04/2017"
}

      

Code to convert user input from String to Date

 DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
  String convertedDate = sdf.format(dateInput.getDateOfJoining());

      

Converting it to the required format, but the return type is String, but the expected Date object to send to the DAO layer. So I tried sdf.parse its returning a Date object but not in the required format

Date date = sdf.parse(sdf.format(dateInput.getDateOfJoining()));
output is like -  Tue Apr 04 00:00:00 IST 2017
expected is 04/04/2017 (with return type Date object).

      

So please help me convert the date object to the required format as the DAO layer expects input as a date object in dd / MM / yyyy format

+6


source to share


3 answers


Edit: Updated answer to match the updated question.

Use the annotation @JsonFormat

from Jackson Databind to specify the date pattern.



public class DateInput
 {
  @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
  private  Date dateOfJoining;
   .......
  }

      

+6


source


change your code to below code snippet



public List setRequestParams(@RequestParam("dateOfJoining")@DateTimeFormat(pattern="dd-MM-yyyy")  DateInput dateInput)
{
   ...
}

      

0


source


With JSON-B (included in Java EE 8), you can do this:

class DateInput {
    @JsonbDateFormat("dd/MM/yyyy")
    public Date dateOfJoining;
}

      

In my tests with Thorntail 2.4, I don't need ISO format annotations when using java.util.Date

:

{
    "dateOfJoining" : "2019-04-28T14:45:15"
}

      

0


source







All Articles