### Question:
GenericRecordSerializer extends JsonSerializer<GenericRecord> { @Override public void serialize(final GenericRecord record, final JsonGenerator gen, final SerializerProvider serializers) throws IOException { gen.writeRawValue(getJsonString(record, record.getSchema())); }  @Override void serialize(final GenericRecord record,
                          final JsonGenerator gen,
                          final SerializerProvider serializers);  }### Answer:
@Test public void shouldSerializeAvroToJsonGivenGenericRecord() throws IOException { Schema.Parser parser = new Schema.Parser(); Schema schema = parser.parse(SCHEMA); GenericRecord record = new GenericData.Record(schema); record.put("name", "kafka"); record.put("created", NOW.toEpochMilli()); Writer jsonWriter = new StringWriter(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(jsonWriter); SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider(); new GenericRecordSerializer().serialize(record, jsonGenerator, serializerProvider); jsonGenerator.flush(); Assertions.assertEquals( "{\"name\":\"kafka\",\"created\":" + NOW.toEpochMilli() + "}" , jsonWriter.toString()); }
@Test public void shouldSerializeAvroToJsonGivenKV() { Schema.Parser parser = new Schema.Parser(); Schema schema = parser.parse(SCHEMA); GenericRecord record = new GenericData.Record(schema); record.put("name", "kafka"); record.put("created", NOW.toEpochMilli()); Json json = Json.getDefault(); final SimpleModule module = new SimpleModule(); module.addSerializer(GenericRecord.class, new GenericRecordSerializer()); json.registerModule(module); String serialized = json.serialize(KV.of("key", record)); System.out.println(serialized); Assertions.assertEquals( "{\"key\":\"key\",\"value\":{\"name\":\"kafka\",\"created\":" + NOW.toEpochMilli() + "}}" , serialized); }
@Test public void shouldSerializeAvroToJsonGivenSpecificRecord() throws IOException { User specificRecord = User.newBuilder().setName("kafka").setCreated(NOW).build(); Writer jsonWriter = new StringWriter(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(jsonWriter); SerializerProvider serializerProvider = new ObjectMapper().getSerializerProvider(); new GenericRecordSerializer().serialize(specificRecord, jsonGenerator, serializerProvider); jsonGenerator.flush(); Assertions.assertEquals( "{\"name\":\"kafka\",\"created\":" + NOW.toEpochMilli() + "}", jsonWriter.toString()); }