I have custom Date
serializer to add certain timezone.
public class DateDeserializer extends StdDeserializer<Date> {
public DateDeserializer() {
this(null);
}
protected DateDeserializer(Class<?> vc) {
super(vc);
}
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
Long dateString = jsonParser.getLongValue();
Date date = new Date(dateString);
changeTimeZone(date);
return date;
}
}
But sometimes the date doesn't come as long
value. Sometimes it comes like String
, for example "2017-01-01"
and method jsonParser.getLongValue()
fails.
Is there some way to know what kind of value jsonParser
is holding? Because if I check jsonParser instanceof String
or long
it always returns false
.
You can use the getCurrentToken()
method and compare with the JsonToken
values :
switch (jsonParser.getCurrentToken()) {
case VALUE_STRING:
// get String value
break;
case VALUE_NUMBER_INT:
// get int or long value
break;
// and so on
}
Or using if
:
if (jsonParser.getCurrentToken() == JsonToken.VALUE_STRING) {
// get String value
} else if (jsonParser.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
// get long value
}
... etc
If your date is String type for example like this mask: "yyyy-MM-dd"
you can use in your deserialize method:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dateString);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.