How to convert Avro GenericRecord to Json using while coverting timestamp fields from milliseconds to datetime?
Currently using Avro 1.8.2
Timestamp tsp = new Timestamp(1530228588182l);
Schema schema = SchemaBuilder.builder()
.record("hello")
.fields()
.name("tsp").type(LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG))).noDefault()
.endRecord();
System.out.println(schema.toString());
GenericRecord genericRecord = new GenericData.Record(schema);
genericRecord.put("tsp",tsp.getTime()); //Assume I cannot change this
System.out.println(genericRecord.toString());
I tried using the function below but the result is same as genericrecord.toString()
public static String toJsonString(Schema schema, GenericRecord genericRecord) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema);
writer.getData().addLogicalTypeConversion(new TimeConversions.TimestampConversion());
JsonEncoder encoder = EncoderFactory.get().jsonEncoder(schema, baos, false);
writer.write(genericRecord, encoder);
encoder.flush();
return baos.toString();
}
Third Attempt
public static GenericRecord deserialize(final Schema schema, byte[] data) throws IOException {
final GenericData genericData = new GenericData(){
@Override
public String toString(Object datum) {
StringBuilder buffer = new StringBuilder();
// Since these types are not quoted and produce a malformed JSON string, quote it here.
if (datum instanceof java.sql.Timestamp || datum instanceof java.sql.Time || datum instanceof java.sql.Date) {
return buffer.append("\"").append(datum).append("\"").toString();
}
return super.toString(datum);
}
};
genericData.addLogicalTypeConversion(new TimeConversions.TimestampConversion());
genericData.addLogicalTypeConversion(new TimeConversions.TimeConversion());
try (final InputStream is = new ByteArrayInputStream(data)) {
final Decoder decoder = DecoderFactory.get().binaryDecoder(is, null);
final DatumReader<GenericRecord> reader = new GenericDatumReader<>(schema, schema, genericData);
return reader.read(null, decoder);
}
}
Schema
{"type":"record","name":"tsp_name","fields":[{"name":"tsp","type":{"type":"long","logicalType":"timestamp-millis"}}]}
Current Output
{"tsp":2018-06-28T23:29:48.182Z} // missing quotes so not a valid json
Expected Output
{"tsp": "2018-06-28T23:29:48.182Z"}