简体   繁体   English

将byteArray转换为string以初始化jsonObject

[英]convert byteArray to string to initialize jsonObject

i have byteArray. 我有byteArray。

is it possible to convert byteArray to String? 是否可以将byteArray转换为String?

please check my code 请检查我的代码

        byte[] data = **some_byte_array**
        JSONObject jsonObject = new JSONObject(data);

how do i fix this. 我该如何解决。

Try this 尝试这个

String decoded = new String(bytes, "UTF-8");

There are a bunch of encodings you can use, look at the Charset class in the Sun javadocs . 您可以使用一堆编码,查看Sun javadocs中的Charset类。

The "proper conversion" between byte[] and String is to explicitly state the encoding you want to use. byte []和String之间的“正确转换”是显式声明要使用的编码。 If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". 如果以byte []开头并且实际上不包含文本数据,则没有“正确的转换”。 Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to. 字符串用于文本,byte []用于二进制数据,唯一真正明智的做法是避免在它们之间进行转换,除非你绝对不得不这样做。

answer credit goes to https://stackoverflow.com/a/1536365/4211264 回复信用转到https://stackoverflow.com/a/1536365/4211264

Yes you can convert byte array to String using one of the String constructors like this : 是的,您可以使用其中一个String构造函数将字节数组转换为String,如下所示:

String myString = new String(yourByteArray);

Documentation for the same: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(byte[]) 文档相同: http//docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(byte [])

All the best :) 祝一切顺利 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM