Java 如何将 GenericRecord 转换为 json 字符串?

Java How to convert a GenericRecord to a json string?

我正在尝试将 GenericRecord 转换为 json 字符串,以便我可以将其传递给 JSONObject 之类的对象。我正在考虑使用 JsonEncoder 来执行此操作。现在我有类似的东西:

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

但是它给我一个错误:

error: incompatible types: ByteArrayOutputStream cannot be converted to JsonGenerator

根据 JsonEncoder 的源代码,它应该有一个接受输出流的构造,所以我不确定为什么会收到此错误。 有人可以建议如何解决这个问题吗?也欢迎关于如何将 GenericRecord 转换为 json 字符串的任何其他建议。谢谢!

如果它是 this JsonEncoder it doesn't have any public constructors. It says to "Construct using EncoderFactory." An EncoderFactory does have a jsonEncoder 工厂方法,需要一个 Schema 和一个 OutputStream

刚刚试了一下,创建JsonEncoder的方法是:

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