如何在Java中使用AVRO序列化日期 [英] How to serialize a Date using AVRO in Java
问题描述
我实际上正在尝试使用Avro序列化包含日期的对象,并且反序列化的日期与预期值不匹配(已通过avro 1.7.2和1.7.1测试).这是我要序列化的课程:
I'm actually trying to serialize objects containing dates with Avro, and the deserialized date doesn't match the expected value (tested with avro 1.7.2 and 1.7.1). Here's the class I'm serializing :
import java.text.SimpleDateFormat;
import java.util.Date;
public class Dummy {
private Date date;
private SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
public Dummy() {
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
@Override
public String toString() {
return df.format(date);
}
}
用于序列化/反序列化的代码:
The code used to serialize / deserialize :
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.avro.Schema;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.reflect.ReflectData;
import org.apache.avro.reflect.ReflectDatumReader;
import org.apache.avro.reflect.ReflectDatumWriter;
public class AvroSerialization {
public static void main(String[] args) {
Dummy expected = new Dummy();
expected.setDate(new Date());
System.out.println("EXPECTED: " + expected);
Schema schema = ReflectData.get().getSchema(Dummy.class);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Encoder encoder = EncoderFactory.get().binaryEncoder(baos, null);
DatumWriter<Dummy> writer = new ReflectDatumWriter<Dummy>(schema);
try {
writer.write(expected, encoder);
encoder.flush();
Decoder decoder = DecoderFactory.get().binaryDecoder(baos.toByteArray(), null);
DatumReader<Dummy> reader = new ReflectDatumReader<Dummy>(schema);
Dummy actual = reader.read(null, decoder);
System.out.println("ACTUAL: " + actual);
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
}
输出:
EXPECTED: 06/11/2012 05:43:29.188
ACTUAL: 06/11/2012 05:43:29.387
它与已知的错误有关,还是与我序列化对象的方式有关?
Is it related to a known bug, or is it related to the way I'm serializing the object ?
推荐答案
我认为AVRO目前尚未序列化日期. 我要做的是将其包装在另一个类中,并在avro人们中存储较长时间(date.gettime()) 添加此功能. 而且您看到不同的Date值的原因是,您(和Avro)每次创建时 一个Date对象,它将使用当前系统时间初始化Date.
I think AVRO doesn't serialize date at this point. What I would do is to wrap it in another class and store at as a long (date.gettime()) while avro folks add this feature. And the reason that you see different Date values is that every time that you (and avro) create a Date object, it initializes the Date with the current System time.
这篇关于如何在Java中使用AVRO序列化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!