JSON 以自定义格式序列化日期(无法从字符串值构造 java.util.Date 的实例)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17655532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)
提问by user739115
could not read JSON: Can not construct instance of java.util.Date from String
value '2012-07-21 12:11:12': not a valid representation("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
passing json request to REST controller method in a POJO class.user should enter only in below datetime format other wise it should throw message.why DateSerializer is not calling?
将 json 请求传递给 POJO 类中的 REST 控制器方法。用户应该只输入以下日期时间格式,否则它应该抛出消息。为什么 DateSerializer 没有调用?
add(@Valid @RequestBody User user)
{
}
json:
json:
{
"name":"ssss",
"created_date": "2012-07-21 12:11:12"
}
pojo class variable
pojo 类变量
@JsonSerialize(using=DateSerializer.class)
@Column
@NotNull(message="Please enter a date")
@Temporal(value=TemporalType.TIMESTAMP)
private Date created_date;
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
logger.info("serialize:"+value);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.info("DateSerializer formatter:"+formatter.format(value));
jgen.writeString(formatter.format(value));
}
采纳答案by lbdfcgyjjr
I have the same problem, so I write a custom date deserialization
with @JsonDeserialize(using=CustomerDateAndTimeDeserialize.class)
我有同样的问题,所以我写了一个自定义日期反序列化 @JsonDeserialize(using=CustomerDateAndTimeDeserialize.class)
public class CustomerDateAndTimeDeserialize extends JsonDeserializer<Date> {
private SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
@Override
public Date deserialize(JsonParser paramJsonParser,
DeserializationContext paramDeserializationContext)
throws IOException, JsonProcessingException {
String str = paramJsonParser.getText().trim();
try {
return dateFormat.parse(str);
} catch (ParseException e) {
// Handle exception here
}
return paramDeserializationContext.parseDate(str);
}
}
回答by Splaktar
Annotate your created_datefield with the JsonFormatannotation to specify the output format.
使用注释对您的created_date字段进行JsonFormat注释以指定输出格式。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = TimeZone.getDefault(), locale = Locale.getDefault())
Note that you may need to pass in a different Locale and TimeZone if they should be based on something other than what the server uses.
请注意,您可能需要传入不同的 Locale 和 TimeZone,如果它们应该基于服务器使用的内容以外的内容。
You can find out more information in the docs.
您可以在文档中找到更多信息。
回答by khoi nguyen
- If you want to bind a
JSONstring to date, this process is calleddeserialization, notserialization. To bind a
JSONstring to date, create a custom date deserialization, annotatecreated_dateor its setter with@JsonDeserialize(using=YourCustomDateDeserializer.class)
- 如果要将
JSON字符串绑定到日期,则此过程称为deserialization,而不是serialization。 要将
JSON字符串绑定到日期,请创建自定义日期反序列化、注释created_date或其设置器@JsonDeserialize(using=YourCustomDateDeserializer.class)
where you have to implement the method public Date deserialize(...)to tell Hymanson how to convert a string to a date.
你必须实现方法public Date deserialize(...)来告诉Hyman逊如何将字符串转换为日期。
Enjoy.
享受。
回答by Dariusz
Yet another way is to have a custom Date object which takes care of its own serialization.
另一种方法是拥有一个自定义 Date 对象,它负责自己的序列化。
While I don't really think extending simple objects like Date, Long, etc. is a good practice, in this particular case it makes the code easily readable, has a single point where the format is defined and is rather more than less compatible with normal Dateobject.
虽然我真的不认为扩展像Date,Long等简单对象是一个很好的做法,但在这种特殊情况下,它使代码易于阅读,具有定义格式的单点,并且与普通Date对象的兼容性相当不错.
public class CustomFormatDate extends Date {
private DateFormat myDateFormat = ...; // your date format
public CustomFormatDate() {
super();
}
public CustomFormatDate(long date) {
super(date);
}
public CustomFormatDate(Date date) {
super(date.getTime());
}
@JsonCreator
public static CustomFormatDate forValue(String value) {
try {
return new CustomFormatDate(myDateFormat.parse(value));
} catch (ParseException e) {
return null;
}
}
@JsonValue
public String toValue() {
return myDateFormat.format(this);
}
@Override
public String toString() {
return toValue();
}
}
回答by rahulnikhare
I solved this by using the below steps.
我通过使用以下步骤解决了这个问题。
1.In entity class annote it using @JsonDeserialize
1.在实体类中使用@JsonDeserialize对其进行注释
@Entity
@Table(name="table")
public class Table implements Serializable {
// Some code
@JsonDeserialize(using= CustomerDateAndTimeDeserialize.class)
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created_ts")
private Date createdTs
}
- Write CustomDateAndTimeDeserialize.java Sample Code
- 编写 CustomDateAndTimeDeserialize.java示例代码
回答by Vikash Kumar
For someone ,If you are using DTO/VO/POJO to map your request you can simply annotate your date field
对于某人,如果您使用 DTO/VO/POJO 来映射您的请求,您可以简单地注释您的日期字段
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date customerRegDate;
And json request should be:
并且 json 请求应该是:
{
"someDate":"2020-04-04 16:11:02"
}
You don't need to annotate Entity class variable.
您不需要注释实体类变量。

