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。
TA贡献1859条经验 获得超6个赞
我使用 JsonFormat 类(com.googlecode.protobuf.format.JsonFormat)来转换 protobuf:
new JsonFormat().printToString(myObject)
这对我来说非常完美。
TA贡献1808条经验 获得超4个赞
包含已从 更改com.googlecode.protobuf.format.JsonFormat
为 com.google.protobuf.util.JsonFormat
因此,如果您的 protobuf 依赖项缺少该format
包,请尝试JsonFormat
在util
.
有了这个包括,你应该能够使用
new JsonFormat().printToString(myObject)
正如@amad-person 所建议的那样。
添加回答
举报