如何将JSONArray中的字节复制到Byte数组

时间:2017-07-16 12:38:45

标签: java android arrays

我以缓冲区(字节)的形式获取图像数据,但我想将其转换为base64字符串。数据在JSONArray中接收,如此

JSONArray : `[53,57,51,47,53,57,51,55,50,98,98,54,53,51,54,97,102,101,53,101,102,54,57,54,53,54,53,51,102,98,53,99,98,98,99,51,98,48,52,57,56,52,52,101,54,48,50,99,56,55,101,54,53,97,51,102,56,49,56,57,56,98,102,56,49,57,97,57]`

为此,我将JSONArray复制到"byte" array,如下所示:

JSONArray bytearray_json = record.getJSONObject("image").getJSONArray("data");
byte[] bytes = new byte[bytearray_json.length()];
for (int i =0; i < bytearray_json.length(); i++ ) {
    bytes[i] = (byte)bytearray_json.get(i);
}
String base_64 = Base64.encodeToString(bytes,Base64.DEFAULT);

但我得到一个例外:Cannot cast Integer to byte 我无法执行bytearray_json.get(i).toString().getBytes();,因为它返回Byte Array

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

你可以试试这个,

JSONArray jsonArray = response.getJSONObject("image").getJSONArray("data");
byte[] bytes = new byte[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
        bytes[i]=(byte)(((int)jsonArray.get(i)) & 0xFF);
}
 Base64.encodeToString(bytes, Base64.DEFAULT);