为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Jackson 将 protobuf 转换为 JSON?

使用 Jackson 将 protobuf 转换为 JSON?

三国纷争 2021-06-13 09:29:53
使用 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:@JsonIgnoreTypeprivate abstract class UnknownFieldSetIgnoreMixIn {}myObjectMapper.addMixIn(UnknownFieldSet.class, UnknownFieldSetIgnoreMixIn.class)
查看完整描述

3 回答

?
动漫人物

TA贡献1815条经验 获得超10个赞

当前序列化 protobuf 的方法(2018 年 10 月)是com.google.protobuf.util.JsonFormat按以下方式使用:


JsonFormat.printer().print(myMessageOrBuilder)

我@JsonSerialize(using = MyMessageSerializer.class)在 protobuf 对象之前使用了注释并添加了这个类:


public static class MyMessageSerializer extends JsonSerializer<Message> {

    @Override

    public void serialize(Message message, JsonGenerator gen, SerializerProvider serializers) throws IOException {

        gen.writeRawValue(JsonFormat.printer().print(message));

    }

}

这允许 new ObjectMapper().writeValueAsString(wrapperObject)将我的 protobuf 正确转换为 JSON。


查看完整回答
反对 回复 2021-06-17
?
慕丝7291255

TA贡献1859条经验 获得超6个赞

我使用 JsonFormat 类(com.googlecode.protobuf.format.JsonFormat)来转换 protobuf:

new JsonFormat().printToString(myObject)

这对我来说非常完美。


查看完整回答
反对 回复 2021-06-17
?
炎炎设计

TA贡献1808条经验 获得超4个赞

包含已从 更改com.googlecode.protobuf.format.JsonFormat 为 com.google.protobuf.util.JsonFormat

因此,如果您的 protobuf 依赖项缺少该format包,请尝试JsonFormatutil.

有了这个包括,你应该能够使用

new JsonFormat().printToString(myObject)

正如@amad-person 所建议的那样。


查看完整回答
反对 回复 2021-06-17
  • 3 回答
  • 0 关注
  • 710 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信