现在正在使用protobuf的时候,但在解析Java中的protobuf消息时仍然会遇到异常,报错如下:
com.google.protobuf.InvalidProtocolBufferException:
While parsing a protocol message, the input ended unexpectedly in the middle of a field.
This could mean either that the input has been truncated or that an embedded message misreported its own length.
当我向redis中存储protobuf序列化后的byte[] 时,发现无法parse回来
stringRedisTemplate.opsForValue()
.set("paper:" + paperId, new String(builder.build().toByteArray()), 30, TimeUnit.MINUTES);
paper = ExamProtobuf.paper.parseFrom(examProtobuf.getBytes());
问题出在java与byte[]转换的过程中。String是带编码的,默认是utf-8,反序列化的时候就报错了。
解决方法:
String 与 byte[] 转换时使用"ISO-8859-1"编码
stringRedisTemplate.opsForValue()
.set("paper:" + paperId, new String(builder.build().toByteArray(), StandardCharsets.ISO_8859_1), 30, TimeUnit.MINUTES);
paper = ExamProtobuf.paper.parseFrom(examProtobuf.getBytes(StandardCharsets.ISO_8859_1));