我正在将RestTemplate和Jackson框架一起用作我的Web服务层。我的数据映射基于注释。
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;
}
}
我该如何进行日期转换?我宁愿有一次编写逻辑并将其应用于所有Date属性的方法,因为这总是我的日期格式。
我无法更改从Web服务返回的日期格式,它已经被我的iPhone客户端使用。
这是我的反序列化器
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;
}
}
这里是用法
@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”,时区=“ UTC”)
此成功,您必须将其配置为数据出价模型
例如:@Temporal(TemporalType.DATE)@JsonFormat(shape = JsonFormat.Shape.STRING,pattern =“ dd / MM / yyyy”,locale =“ pt-BR”,时区=“ UTC”)私有字符串expiryDate;