3 回答

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
當(dāng)前序列化 protobuf 的方法(2018 年 10 月)是com.google.protobuf.util.JsonFormat按以下方式使用:
JsonFormat.printer().print(myMessageOrBuilder)
我@JsonSerialize(using = MyMessageSerializer.class)在 protobuf 對象之前使用了注釋并添加了這個(gè)類:
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 正確轉(zhuǎn)換為 JSON。

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊
我使用 JsonFormat 類(com.googlecode.protobuf.format.JsonFormat)來轉(zhuǎn)換 protobuf:
new JsonFormat().printToString(myObject)
這對我來說非常完美。

TA貢獻(xiàn)1808條經(jīng)驗(yàn) 獲得超4個(gè)贊
包含已從 更改com.googlecode.protobuf.format.JsonFormat
為 com.google.protobuf.util.JsonFormat
因此,如果您的 protobuf 依賴項(xiàng)缺少該format
包,請嘗試JsonFormat
在util
.
有了這個(gè)包括,你應(yīng)該能夠使用
new JsonFormat().printToString(myObject)
正如@amad-person 所建議的那樣。
添加回答
舉報(bào)