You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@avro.apache.org by umahida <ur...@gmail.com> on 2014/10/21 19:11:10 UTC

Converting POJO to Generic or Indexed Records

HI ,
I have complicated nested POJOs. I am able to generate the schema using
ReflectData tool. 
I want to convert them to Generic Record preferably or Indexed Records. I
dnt want to hand code and set each and every nested member.
I there a way similar to reflection where I can convert POJOs to generic
record say through a API call or similar. The generated schema through
reflection can be used here I guess.



--
View this message in context: http://apache-avro.679487.n3.nabble.com/Converting-POJO-to-Generic-or-Indexed-Records-tp4031183.html
Sent from the Avro - Users mailing list archive at Nabble.com.

Re: Converting POJO to Generic or Indexed Records

Posted by Doug Cutting <cu...@apache.org>.
On Tue, Oct 21, 2014 at 10:11 AM, umahida <ur...@gmail.com> wrote:
> I have complicated nested POJOs. I am able to generate the schema using
> ReflectData tool.
> I want to convert them to Generic Record preferably or Indexed Records.


To convert from a reflect representation to generic you can serialize
instances with ReflectDatumWriter then read them with
GenericDatumReader.  For example, something like:

public Object reflectToGeneric(Object object, Schema s) {
    ReflectDatumWriter<Object> writer = new ReflectDatumWriter<Object>(s);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    writer.write(object, EncoderFactory.get().directBinaryEncoder(out, null));
    GenericDatumReader<Object> reader = new GenericDatumReader<Object>(s);
    return reader.read(null,
DecoderFactory.get().binaryDecoder(out.toByteArray(), null));
}

If you're converting multiple objects it would be faster to reuse the
writer, reader, encoder, decoder, etc.

Doug