如何在 Java 中将 Protobuf ByteString 转换为 String

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44325896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:30:20  来源:igfitidea点击:

How to Convert Protobuf ByteString to String in java

javaprotocol-buffers

提问by Dinesh Kumar J

Could anyone please let me know how to convert protobuf ByteString to String in java?

谁能告诉我如何在java中将protobuf ByteString转换为String?

In my case, I am getting the ByteString value as "\376\024\367". Is there a way to get the same as String from ByteString? I meant when I print the string value in console using System.out.println(), I should get \376\024\367.

就我而言,我得到的 ByteString 值为“\376\024\367”。有没有办法从 ByteString 获得与 String 相同的值?我的意思是当我使用 System.out.println() 在控制台中打印字符串值时,我应该得到 \376\024\367。

Many thanks.

非常感谢。

采纳答案by Kenton Varda

Normally, you'd convert a ByteString to a String using ByteString#toString(Charset). This method lets you specify what charset the text is encoded in. If it's UTF-8, you can also use the method toStringUtf8()as a shortcut.

通常,您会使用 将 ByteString 转换为 String ByteString#toString(Charset)。此方法可让您指定文本的编码字符集。如果是 UTF-8,您还可以使用该方法toStringUtf8()作为快捷方式。

From your question, though, it sounds like you actually want to produce the escaped format using C-style three-digit octal escapes. AFAIK there's no public function to do this, but you can see the code here. You could copy that code into your own project and use it.

但是,从您的问题来看,听起来您实际上想使用 C 样式的三位数八进制转义符来生成转义格式。AFAIK 没有公共功能可以执行此操作,但您可以在此处查看代码。您可以将该代码复制到您自己的项目中并使用它。

回答by Vitaliy Hnatyk

I have used http://doc.akka.io/japi/akka/2.3.7/akka/util/ByteString.ByteStrings.htmlYou will see to method decodeString(java.lang.String charset)

我用过http://doc.akka.io/japi/akka/2.3.7/akka/util/ByteString.ByteStrings.html你会看到方法decodeString(java.lang.String charset)

else see to https://github.com/akka/akka/issues/18738

其他见https://github.com/akka/akka/issues/18738