如何将dateOfJoining值(字符串类型)绑定到成员变量" dateOfJoining"(日期类型)" DateInput"通过邮递员发送到JSON以下的课程。如何使用相同的格式dd / MM / yyyy将String中的String转换为Date对象。转换日期应该在Date对象中,而不是String。
Json如下所示
{
"dateOfJoining" : "03/04/2017"
}
服务URL在postman中命中 - localhost / Rest / hello
java中的RestService类 - HandleRestRequest.java
@RestController
public class HandleRestRequest
{
@RequestMapping("\hello");
public List setRequestParams(@RequestBody DateInput dateInput)
{
.......
}
}
Pojo Class DateInput.java
public class DateInput
{
private Date dateOfJoining;
.......
}
如果我以下面的格式从json发送日期,则其投掷错误为输入不满意
{
"dateOfJoining" : 04/04/2017
}
所以我将它作为字符串格式发送,并将dateOfJoining更改为DateInput.java文件中的字符串,稍后我尝试将其转换为日期对象,如下所示
从Date到String修改DateInput.java文件
public class DateInput
{
private String dateOfJoining;
.......
}
修改了JSON
{
"dateOfJoining" : "04/04/2017"
}
将用户输入从String转换为Date
的代码 DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String convertedDate = sdf.format(dateInput.getDateOfJoining());
它转换为所需的格式但返回类型是String但是期望是发送DAO层的Date对象。所以我尝试了sdf.parse,它返回Date对象但不是必需的格式
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).
所以请帮助我如何将字符串转换为具有所需格式的日期对象,因为DAO层期望输入为日期对象,格式为dd / MM / yyyy
答案 0 :(得分:8)
编辑:根据更新的问题更新答案。
使用Jackson Databind中的注释@JsonFormat
指定日期模式。
public class DateInput
{
@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
private Date dateOfJoining;
.......
}
答案 1 :(得分:0)
将您的代码更改为以下代码段
public List setRequestParams(@RequestParam("dateOfJoining")@DateTimeFormat(pattern="dd-MM-yyyy") DateInput dateInput)
{
...
}
答案 2 :(得分:0)
使用JSON-B(包含在Java EE 8中),您可以执行以下操作:
$client = new Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST =>0), ));
$res = $client->request('GET', 'https://assignment-api.uspto.gov/patent/basicSearch?query='.$request->input('query'));
$respons = $res->getBody()->getContents();
// dd($respons);
$xml = XmlParser::extract($respons);
$doc = $xml->parse([
'publNum' => ['uses' => 'result.publNum'],
'inventionTitle' => ['uses' => 'result.inventionTitle'],
'inventors' => ['uses' => 'result.inventors'],
'corrName' => ['uses' => 'result.corrName'],
'corrAddress1' => ['uses' => 'result.corrAddress1'],
'corrAddress2' => ['uses' => 'result.corrAddress2'],
'corrAddress3' => ['uses' => 'result.corrAddress3'],
'patAssigneeName' => ['uses' => 'result.patAssigneeName'],
'patAssigneeAddress1' => ['uses' => 'result.patAssigneeAddress1'],
'patAssigneeAddress2' => ['uses' => 'result.patAssigneeAddress2'],
'patAssigneeCity' => ['uses' => 'result.patAssigneeCity'],
'patAssigneeState' => ['uses' => 'result.patAssigneeState'],
'patAssigneeCountryName' => ['uses' => 'result.patAssigneeCountryName'],
]);
dd($doc);
在使用Thorntail 2.4进行的测试中,使用class DateInput {
@JsonbDateFormat("dd/MM/yyyy")
public Date dateOfJoining;
}
时不需要ISO格式的任何注释:
java.util.Date