使用JSONObject放置/获取字节数组值 [英] Put/get byte array value using JSONObject
问题描述
我尝试使用以下代码从JSONObject
中获取我的byte[]
值,但我没有获得原始的byte[]
值.
I tried to get my byte[]
value from JSONObject
using following code but I am not getting original byte[]
value.
JSONArray jSONArray = jSONObject.getJSONArray(JSONConstant.BYTE_ARRAY_LIST);
int len = jSONArray.length();
for (int i = 0; i < len; i++) {
byte[] b = jSONArray.get(i).toString().getBytes();
//Following line creates pdf file of this byte arry "b"
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
}
}
以上代码创建了pdf文件,但文件无法打开,即损坏的文件.当我使用相同的类和方法创建文件时:
Above code creates pdf file but file can not open i.e corrupted file. When I use same class and method to create file:
FileCreator.createPDF(b, "test PDF From Web Resource.pdf");
在添加到JSONObject
中之前,如下所示:
before adding into JSONObject
like follwoing:
JSONObject jSONObject = new JSONObject();
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST, bList);
它会创建文件,即我可以打开pdf文件并读取其内容.
it creates file i.e I can open pdf file and read its content.
从JSONObject
获取byte[]
以便创建损坏的文件,我做错了什么?请指导我.我一直欢迎发表评论.谢谢.
What I did wrong to get byte[]
from JSONObject
so that it is creating corrupted file? Please kindly guide me. And I always welcome to comments. Thank You.
推荐答案
最后,我在 apache commons 库的帮助下解决了我的问题.首先,我使用了以下依赖性.
Finally I solved my issue with the help of apache commons library. First I used following dependency.
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.6</version>
<type>jar</type>
</dependency>
我以前使用的技术对我来说是错误的(不确定其他).以下是解决问题的方法.
The technique that I was using previously was wrong for me (Not sure for other). Following is the solution how I solved my problem.
解决方案:
我以前在JSONObject上添加了字节数组值,并存储为String.当我尝试从JSONObject获取到我的字节数组时,它返回String而不是我的原始字节数组.而且即使我使用以下命令也没有得到原始的字节数组:
byte[] bArray=jSONObject.getString(key).toString().getBytes();
现在
首先,我将字节数组编码为字符串,并在JSONObject上保留为该编码的字符串.见下文:
First I encoded my byte array into string and kept on JSONObject to that encoded string. See below:
byte[] bArray=(myByteArray);
//Following is the code that encoded my byte array and kept on String
String encodedString = org.apache.commons.codec.binary.Base64.encodeBase64String(bArray);
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST , encodedString);
还有我得到的原始字节数组的代码:
String getBackEncodedString = jSONObject.getString(JSONConstant.BYTE_ARRAY_LIST);
//Following code decodes to encodedString and returns original byte array
byte[] backByte = org.apache.commons.codec.binary.Base64.decodeBase64(getBackEncodedString);
//Creating pdf file of this backByte
FileCreator.createPDF(backByte, "fileAfterJSONObject.pdf");
就是这样.
这篇关于使用JSONObject放置/获取字节数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!