Hey Check,

I asked a very similar question a few days ago and Dave McAlpin (
dmcal...@inome.com) was able to help with. He sent out a couple
general-purpose serialization and deserialization functions for JSON to
String and back to JSON, but this can be adapted to JSON->byte[]->JSON
easily:

Here are some utility functions we've used for serialization to and from
JSON. Something similar should work for binary.



public <T> String avroEncodeAsJson(Class<T> clazz, Object object) {

    String avroEncodedJson = null;

    try {

        if (object == null || !(object instanceof SpecificRecord)) {

            return null;

        }

        T record = (T) object;

        Schema schema = ((SpecificRecord) record).getSchema();

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        Encoder e = EncoderFactory.get().jsonEncoder(schema, out);

        SpecificDatumWriter<T> w = new SpecificDatumWriter<T>(clazz);

        w.write(record, e);

        e.flush();

        avroEncodedJson = new String(out.toByteArray());

    } catch (IOException e) {

        e.printStackTrace();

    }



    return avroEncodedJson;

}



public <T> T jsonDecodeToAvro(String inputString, Class<T> className,
Schema schema) {

    T returnObject = null;

    try {

        JsonDecoder jsonDecoder = DecoderFactory.get().jsonDecoder(schema,
inputString);

        SpecificDatumReader<T> reader = new
SpecificDatumReader<T>(className);

        returnObject = reader.read(null, jsonDecoder);

    } catch (IOException e) {

        e.printStackTrace();

    }



    return returnObject;
}

Hope that helps,
Gary


On Mon, Feb 24, 2014 at 9:54 AM, Check Peck <comptechge...@gmail.com> wrote:

>
> On Mon, Feb 24, 2014 at 7:43 AM, Adrian Hains <aha...@gmail.com> wrote:
>
>> org.apache.avro.tool.DataFileWriteTool
>>
>
>
> I just read it and the description says "Reads new-line delimited JSON
> records and writers an Avro data file."
>
> And I need to Avro Binary Encode my JSON String into ByteArray and I guess
> they both are different correct?
>

Reply via email to