avro 序列化java,如何在Java中使用AVRO序列化日期

博客讨论了使用Avro进行对象序列化时遇到日期不匹配的问题。作者发现即使输入相同的日期,反序列化后得到的日期值不同。原因在于每次创建Date对象时会初始化为当前系统时间。解决方案是将日期包装在另一个类中,存储为long类型(date.getTime()),直至Avro官方添加日期支持。
摘要由CSDN通过智能技术生成

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 writer = new ReflectDatumWriter(schema);

try {

writer.write(expected, encoder);

encoder.flush();

Decoder decoder = DecoderFactory.get().binaryDecoder(baos.toByteArray(), null);

DatumReader reader = new ReflectDatumReader(schema);

Dummy actual = reader.read(null, decoder);

System.out.println("ACTUAL: " + actual);

} catch (IOException e) {

System.err.println("IOException: " + e.getMessage());

}

}

}

And the output :

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 ?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值