Search code examples
javajsonavro

Java How to convert a GenericRecord to a json string?


I am trying to convert a GenericRecord to a json string so I can pass it to something like a JSONObject. I am thinking about using the JsonEncoder to do this. Right now I have something like:

ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonEncoder jsonEncoder = new JsonEncoder(genericRecord.getSchema(),out);

However it's giving me an error:

error: incompatible types: ByteArrayOutputStream cannot be converted to JsonGenerator

Per the source code of JsonEncoder it should have a construct that takes in a outputstream so I am not sure why I am getting this error. Can someone suggest how to fix the problem? Any other suggestion on how to convert a GenericRecord to a json string is also welcome. Thanks!


Solution

  • If it's this JsonEncoder it doesn't have any public constructors. It says to "Construct using EncoderFactory." An EncoderFactory does have a jsonEncoder factory method that takes a Schema and an OutputStream, though.

    I just tried it out, and the way to create a JsonEncoder is:

    JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(genericRecord.getSchema(), out);