2017-08-15 27 views
0

的方式我有這樣JSON圖像響應:差之間的兩個轉換JSON的ByteArray

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

在第二種方式,我可以字節組轉換爲位圖:

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

但在第一種方式該位爲空。 我想知道這兩種方式之間的區別在哪裏?

回答

1

第一種方法調用resultImage.toString.getBytes。這將創建一個JSON字符串,然後爲您提供其中包含的每個字符的ASCII值。

對於"[42]"你會得到這些字節:[0x5B, 0x34, 0x32, 0x5D]。他們都是錯的,而且他們太多了。您的BitmapFactory將拒絕它。

第二種方法按元素遍歷數組元素,將在那裏找到的數字視爲字節值並構造這些值的新數組。

對於"[42]"你會得到[0x2A](這是你想要的)。