Java 将字节数组转换为 JSONArray 的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26098861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:50:44  来源:igfitidea点击:

simple way to convert byte array to JSONArray

javabytearrayarrays

提问by Vithushan

I have a byte array which was converted from a JSONArray. Now how to convert it back to JSONArray. Is there any simple lib to do this. Or do i have to use base64 as thispost says? Here is the code to convert JSONArray to bytearray:

我有一个从 JSONArray 转换而来的字节数组。现在如何将其转换回 JSONArray。有没有简单的库来做到这一点。或者我必须像这篇文章所说的那样使用 base64吗?这是将 JSONArray 转换为 bytearray 的代码:

JSONArray arr = //some value;
byte[] bArr = arr.toString().getBytes();

采纳答案by blackSmith

Since you are not specifying no CharSeton converting the Json array string to bytes. Simply use :

由于您没有CharSet在将 Json 数组字符串转换为字节时指定 no 。只需使用:

   arr = new JSONArray(new String(bArr));

回答by Rohit

The typical way to send binary in json is to base64 encode it. Java provides different ways to Base64 encode and decode a byte[]. One of these is DatatypeConverter.

在 json 中发送二进制文件的典型方法是对它进行 base64 编码。Java 提供了不同的 Base64 编码和解码字节 [] 的方法。其中之一是DatatypeConverter。

Very simply

很简单

byte[] originalBytes = new byte[] { 1, 2, 3, 4, 5};
String base64Encoded = DatatypeConverter.printBase64Binary(originalBytes);
byte[] base64Decoded = DatatypeConverter.parseBase64Binary(base64Encoded);