[英]How to get Calendar field from REST request in RestController in SpringBoot?
I am getting date in POST request in @RestController
with Json like this: { "date":"2016-01-28" }
How can I get object with type java.util.Calendar
? 我在Json的@RestController
中的POST请求中获取日期,如下所示: { "date":"2016-01-28" }
如何获取类型为java.util.Calendar
对象? Usually I use java.util.Date
, but almost all methods are deprecated. 通常我使用java.util.Date
,但是几乎所有方法都已弃用。 What Jackson annotation possible to use to get Calendar
? 可以使用什么Jackson注释来获取Calendar
? I tried to use 我尝试使用
public class Test {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
Calendar date;
}
but get null
但得到null
You can use annotation @DateTimeFormat
. 您可以使用注释@DateTimeFormat
。 According to Spring docs it's applicable to java.util.Calendar
. 根据Spring 文档,它适用于java.util.Calendar
。
@PostMapping("/somemapping")
public void date(@RequestParam("date") @DateTimeFormat(pattern = "yyyy-MM-dd") Calendar date) {
//some other processing code
}
I would suggest using a java.util.Date
instead of a Calendar
. 我建议使用java.util.Date
代替Calendar
。 At least in your repository object. 至少在您的存储库对象中。 If you need the additional functionality of a Calendar you can create an instance as demonstrated by @Hamza
. 如果您需要日历的其他功能,则可以创建一个实例,如@Hamza
。
Calendar
is a pretty heavy-weight class. Calendar
是一门非常重量级的课程。 No need to create a new instance of it considering the tiny amount of data you are storing. 考虑到要存储的数据量很少,因此无需创建新实例。
You can pick out the date from another class that operates on it to provide you the additional functionality as required. 您可以从对其进行操作的另一个类中选择日期,以根据需要为您提供其他功能。
{
"calendar": 1558347802873
}
Sample json request 样本JSON请求
just pass date in number format use below object 只是以数字格式传递日期,在对象下面使用
import java.util.Calendar;
public class TestCal {
private Calendar calendar;
public Calendar getCalendar() {
return calendar;
}
public void setCalendar(Calendar calendar) {
this.calendar = calendar;
}
}
sample spring Controller 样品弹簧控制器
@PostMapping("/testCal")
public void testCal(@RequestBody TestCal test) {
// do your stuff
test.getCalendar();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.