/** * Standard Avro/JSON encoder. * * @param value Avro value to encode. * @param schema Avro schema of the value. * @return JSON-encoded value. * @throws IOException on error. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static String toAvroJsonString(Object value, Schema schema) throws IOException { try { final ByteArrayOutputStream jsonOutputStream = new ByteArrayOutputStream(); final JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, jsonOutputStream); final GenericDatumWriter writer = new GenericDatumWriter(schema); writer.write(value, jsonEncoder); jsonEncoder.flush(); return AvroUtils.toString(jsonOutputStream.toByteArray()); } catch (IOException ioe) { throw new RuntimeException("Internal error: " + ioe); } }
Preconditions.checkArgument(schema.getType() == Schema.Type.UNION); final Schema optionalType = AvroUtils.getOptionalType(schema); if (null != optionalType) { return (null == value)
final Schema optionalType = AvroUtils.getOptionalType(schema); if (optionalType != null) { return json.isNull() ? null : fromJsonNode(json, optionalType);
/** * Standard Avro/JSON encoder. * * @param record Avro record to encode. * @return JSON-encoded value. * @throws IOException on error. */ @SuppressWarnings({"rawtypes", "unchecked"}) public static String toAvroJsonString(IndexedRecord record) throws IOException { final Schema schema = record.getSchema(); try { final ByteArrayOutputStream jsonOutputStream = new ByteArrayOutputStream(); final JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, jsonOutputStream); final SpecificDatumWriter writer = new SpecificDatumWriter(record.getClass()); writer.write(record, jsonEncoder); jsonEncoder.flush(); return AvroUtils.toString(jsonOutputStream.toByteArray()); } catch (IOException ioe) { throw new RuntimeException("Internal error: " + ioe); } } }