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));

你可能感兴趣的:(java)