两种转换方式的区别 JSON byteArray

difference between two way of converting JSON byteArray

我有 json 这样的图像响应:

"UserImage":[
255,
216,
255,
224,
0,.....]

我有两种方式来响应字节数组:

1 -

        JSONArray resultImage = result.getJSONArray("UserImage");
        byte[] byteUserImage = resultImage.toString().getBytes();
        hashUserImageMap.put(userId, byteUserImage);

2-

            byte[] tmp=new byte[result.getJSONArray("UserImage").length()];
        for(int i=0;i<result.getJSONArray("UserImage").length();i++){
            tmp[i]=(byte)(((int)result.getJSONArray("UserImage").get(i)) & 0xFF);
        }
        hashUserImageMap.put(userId, tmp);

第二种方法我可以将 byteArray 转换为位图:

byte[] arr = getMapInstance().get(name);                 
Bitmap bitmap = BitmapFactory.decodeByteArray(arr, 0, arr.length);

但首先这个位图是空的。 我想知道这些牵引方式之间的区别在哪里?

第一个方法调用resultImage.toString.getBytes。这将创建一个 JSON 字符串,然后为您提供其中包含的每个字符的 ASCII 值。

对于 "[42]",您将获得这些字节:[0x5B, 0x34, 0x32, 0x5D]。他们都错了,而且太多了。你的 BitmapFactory 会拒绝它。

第二种方法逐个元素遍历数组,将在那里找到的数字视为字节值并构造一个包含这些值的新数组。

对于"[42]"你会得到[0x2A](这就是你想要的)。