Question

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.

Was it helpful?

Solution

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;
}

OTHER TIPS

@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;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top