I am using RestTemplate along with Jackson framework as my web service layer. My Data mapping is annotation based.
public class User {
private String name;
private Date dateOfBirth;
@JsonProperty("Name")
public void setName(String name) {
this.name = name;
}
// Value coming back from MVC.Net "/Date(1381302000000)/"
@JsonProperty("DatOfBirth")
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
How can I do this date conversion? I rather have a way to write the logic once and apply to all Date properties since this si always my date format.
I can't change the date format coming back from web service, it's already being used by my iPhone client.
Here is my deserializer
public class DateDeserializer extends JsonDeserializer<Date>
{
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext arg1) throws IOException, JsonProcessingException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
String msDateString = node.getValueAsText();
if (msDateString == null || msDateString.length() == 0)
return null;
String unicodeDateString = msDateString.substring(msDateString.indexOf("(")+1);
unicodeDateString = unicodeDateString.substring(0, unicodeDateString.indexOf(")"));
Date date = new Date(Long.valueOf(unicodeDateString) * 1000);
return date;
}
}
Here is the usage
@JsonDeserialize(using = DateDeserializer.class)
@JsonProperty("DatOfBirth")
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Temporal(TemporalType.DATE) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", locale = "pt-BR", timezone = "UTC")
This one sucess and you have to configure this in to your data biding model
Ex: @Temporal(TemporalType.DATE) @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", locale = "pt-BR", timezone = "UTC") private String expiryDate;
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.