用JSON 传输byte数组


今晚上在编写udp传输文件的时候发现无法用JSON传输字节数组,试了很多种办法都会报错,最后查资料找到了Base64这个类,这个类可以将字节数组转为字符串,在JSON中传输以后可以再转化为字节数组。

写个小例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package  test;
 
import  java.util.Base64;
 
public  class  testStringAndbyte
{
 
     public  static  void  main(String[] args)
     {
         // TODO Auto-generated method stub
         byte  [] s1 = { 0 , 1 , 0 };
          String FileBuf = Base64.getEncoder().encodeToString(s1);
          System.out.println(FileBuf);
          byte [] s2 = {};
          s2 = Base64.getDecoder().decode(FileBuf);
          for ( int  i = 0 ;i<s2.length;i++)
          {
              System.out.print(s2[i]);
          }
         
     }
 
}

  运行结果如下所示:

 

 这样的话就可以使用JSON格式传送字节数组了。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM