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

偶尔善良 提交于 2019-12-12 06:37:35

问题


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 (rather 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.


回答1:


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?




回答2:


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


来源:https://stackoverflow.com/questions/5489083/how-can-i-make-jackson-deserialize-a-long-to-a-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!