使用 Jackson 将 protobuf 转换为 JSON?

使用 Jackson 的 ObjectMapper 将 protobuf 转换为 JSON 时出现以下错误:


com.fasterxml.jackson.databind.exc.InvalidDefinitionException: 

Direct self-reference leading to cycle (through reference chain:

MyObjectPb$MyObject["unknownFields"]->

com.google.protobuf.UnknownFieldSet["defaultInstanceForType"])

MyObjectPb 具有以下字段:


protected com.google.protobuf.UnknownFieldSet unknownFields

在处理现有代码库时,我有以下限制:


我无法修改 MyObjectPb 的源代码,因此我无法在 MyObjectPb 中使用 Jackson 的 ignore 注释。

我也不能使用 Gson 的库来转换对象,因为代码库已经使用 Jackson 进行序列化。不建议添加新的依赖项。

我如何告诉 Jackson 忽略(反)序列化 MyObjectPb 中的 UnknownFieldSet 对象?


我尝试了以下方法,但这些方法似乎无法解决问题:


a) 配置 ObjectMapper:


myObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

myObjectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

b) 使用 Jackson Mixin:


@JsonIgnoreType

private abstract class UnknownFieldSetIgnoreMixIn {}


myObjectMapper.addMixIn(UnknownFieldSet.class, UnknownFieldSetIgnoreMixIn.class)


三国纷争
浏览 711回答 3
3回答

动漫人物

当前序列化 protobuf 的方法(2018 年 10 月)是com.google.protobuf.util.JsonFormat按以下方式使用:JsonFormat.printer().print(myMessageOrBuilder)我@JsonSerialize(using = MyMessageSerializer.class)在 protobuf 对象之前使用了注释并添加了这个类:public static class MyMessageSerializer extends JsonSerializer<Message> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void serialize(Message message, JsonGenerator gen, SerializerProvider serializers) throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; gen.writeRawValue(JsonFormat.printer().print(message));&nbsp; &nbsp; }}这允许 new ObjectMapper().writeValueAsString(wrapperObject)将我的 protobuf 正确转换为 JSON。

慕丝7291255

我使用 JsonFormat 类(com.googlecode.protobuf.format.JsonFormat)来转换 protobuf:new&nbsp;JsonFormat().printToString(myObject)这对我来说非常完美。

炎炎设计

包含已从 更改com.googlecode.protobuf.format.JsonFormat&nbsp;为&nbsp;com.google.protobuf.util.JsonFormat因此,如果您的 protobuf 依赖项缺少该format包,请尝试JsonFormat在util.有了这个包括,你应该能够使用new&nbsp;JsonFormat().printToString(myObject)正如@amad-person 所建议的那样。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java