开发者

How can I make Jackson deserialize a Long to a Date Object?

开发者 https://www.devze.com 2023-02-20 15:41 出处:网络
I\'m serializing some java.util.Dates within a Map. The dates are serialized into Longs (Jackson writes the Long value of the Date instance to the JSON string), however, they\'re not being de-serializ

I'm serializing some java.util.Dates within a Map. The dates are serialized into Longs (Jackson writes the Long value of the Date instance to the JSON string), however, they're not being de-serialized back to Date instances, but as Long instances.

I'd like Jackson to de-serialize the dates back to Date objects (rathe开发者_StackOverflow中文版r than formatted Strings or Longs), how can I achieve this?

Map<String, Comparable<?>> change = new HashMap<String, Comparable<?>>();
    change.put("DESCRIPTION", "LIBOR");
    change.put("RATE", "1.8");
    change.put("DATE", Util.newDate(2009, 7, 1)); // Returns a java.util.Date

Produces

{"DESCRIPTION":"LIBOR"},{"RATE":"1.8"},{"DATE":1246402800000}, ... }

Which is okay. However, the date String is deserialized (inflated) back into an instance of java.lang.Long, when I want it to be an instance of java.util.Date - which is what it started as. i.e. Map change now contains three entries; Description as a String, Rate as a Float and Date as a Long.


You want to use org.codehaus.jackson.map.JsonDeserializer and write the custom deserialization code. Something like:

public class DateDeserializer extends JsonDeserializer<Long> {
    @Override
    public Long deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
       ... custom logic
    }
}

I guess you have to figure out when a Long property has to be deserialized to Date. Maybe using annotations on your pojos?


I don't know if a String representation of the Date would be of any help?

If yes, then you could try setting the DateFormat on the ObjectMapper. The deserialization would then be in the readable String format.

E.g for the below code, the output would be like [{"birthDate":"March 30, 2011"}]

    @Test
public void testJsonConvertDate(){

    ObjectMapper mapper = new ObjectMapper();
    mapper.getSerializationConfig().setDateFormat(DateFormat.getDateInstance(DateFormat.LONG));
    StringWriter stringWriter = new StringWriter();
    try {
        mapper.writeValue(stringWriter, Arrays.asList(new TestUser(new Date())));
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(stringWriter.toString());
}

private class TestUser {
    Date birthDate;

    private TestUser(Date birthDate) {
        this.birthDate = birthDate;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号