Jackson 2 - 在Android上使用Retrofit REST-API将String直接反序列化为Date

时间:2014-08-08 22:02:11

标签: android date jackson retrofit

我正在将包含java.util.Date的json反序列化为字符串,格式为“yyyy-MM-dd HH:mm:ss”。我的目标是将其解析为日期,因此我可以稍后以java.util.Date访问它。

我的POJO包含以下内容:

@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
    "id",
    "dateTime",
    "currentPeriod",
    (...)
})
public class MatchItem {

    @JsonProperty("id")
    private int id;

    @JsonProperty("dateTime")
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss", 
    private Date dateTime;

    @JsonProperty("currentPeriod")
    private int currentPeriod;

    (...)

    @JsonProperty("dateTime")
    public Date getDateTime() {
        return dateTime;
    }

    @JsonProperty("dateTime")
    public void setDateTime(Date dateTime) {
        this.dateTime = dateTime;
    }

然后我使用REST API(Retrofit)直接反序列化我的服务器json响应。将日期保留为字符串格式是可行的,但是当我尝试将其直接反序列化为java.util.Date时,它不会吗?

我怎样才能让它发挥作用?

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

最后,我没有找到一种方法来做我只想做杰克逊注释的事情,我通过实施改造的自定义转换器来解决这个问题:

JacksonConverter matchItemConverter = new JacksonConverter(Utils.getHwObjectMapper());
RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(URL)
    .setConverter(matchItemConverter)
    .build();

创建objectmapper时,请务必添加日期格式:

public static ObjectMapper getHwObjectMapper() {
    ObjectMapper hWObjectMapper = new ObjectMapper();
    hWObjectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH));
    return hWObjectMapper;
}

根据杰克逊制作你的转换器:

public class JacksonConverter implements Converter {
private final ObjectMapper mapper;

public JacksonConverter(ObjectMapper mapper) {
    this.mapper = mapper;
}

@Override public Object fromBody(TypedInput body, Type type) throws ConversionException
{
    String charset = "UTF-8";
    if (body.mimeType() != null) {
        charset = MimeUtil.parseCharset(body.mimeType());
    }

    InputStreamReader isr = null;
    try {
        isr = new InputStreamReader(body.in(), charset);
        return mapper.readValue(isr, TypeFactory.rawClass(type));
    } catch (IOException e) {
        throw new ConversionException(e);
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException ignored) {
                ignored.printStackTrace();
            }
        }
    }
}

@Override public TypedOutput toBody(Object object) {
    try {
        return new JsonTypedOutput(mapper.writeValueAsBytes(object));
    } catch (JsonProcessingException e) {
        throw new AssertionError(e);
    }
}

private static class JsonTypedOutput implements TypedOutput {
    private final byte[] jsonBytes;

    JsonTypedOutput(byte[] jsonBytes) {
        this.jsonBytes = jsonBytes;
    }

    @Override public String fileName() {
        return null;
    }

    @Override public String mimeType() {
        return "application/json; charset=UTF-8";
    }

    @Override public long length() {
        return jsonBytes.length;
    }

    @Override public void writeTo(OutputStream out) throws IOException {
        out.write(jsonBytes);
    }
}
}