有一个客户端使用 protobuf 序列化一些值。这个客户端是用python编程的。我使用套接字将序列化结果发送到 Java 代码:
serializedRow = t_event.SerializeToString()
sock.send(serializedRow)
在 java 代码中,消息作为字符串接收,但在“ParseFrom”函数的步骤中,存在一些不明确的错误。由于 ParseFrom 的参数是 Bytes,因此在传递字符串之前,它会被转换为 Bytes。
byte[] bytes = row.getBytes();
TaxiEvent taxiEvent1 = TaxiEvent.ParseFrom(bytes);
int sec = taxiEvent1.getTripTimeInSecs();
java代码运行在Apache Flink的上下文中,导致报错信息很长而且不清晰。但是当我省略 parsefrom 行时,没有发生错误,显然通过省略这一行接收到的数据无法使用。
protobuf的版本是3.5.0。
最佳答案
一种解决方案是使用 protobuf-java 提供的
.Json.Printer
和 Json.Parser
类在 JSON
中序列化/反序列化-util
Java 实现
添加这个依赖:
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java-util</artifactId>
<version>3.8.0</version>
</parent>
代码示例:
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.util.JsonFormat;
public class EventHelper {
private static final JsonFormat.Printer PRINTER = JsonFormat.printer();
private static final JsonFormat.Parser PARSER = JsonFormat.parser();
public static String toFunctionId(Event event) throwsInvalidProtocolBufferException {
return PRINTER.print(event);
}
public static Event toEvent(String functionId) throws InvalidProtocolBufferException {
Event.Builder builder = Event.newBuilder();
PARSER.merge(functionId, builder);
return builder.build();
}
}
关于java - 如何在 java 中使用 protobuf 获取和解析序列化字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48466046/