使用 JSONObject 放置/获取字节数组值

2022-01-21 00:00:00 arrays pdf java jersey

我尝试使用以下代码从 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. But, 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 added the 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 上添加了字节数组值并存储为字符串.当我尝试从 JSONObject 获取到我的字节数组时,它返回 String 而不是我的原始字节数组.即使我使用以下内容也没有得到原始字节数组:

byte[] bArray=jSONObject.getString(key).toString().getBytes();

现在,

首先,我将字节数组编码为字符串并保存在 JSONObject 上.见下文:

First I encoded my byte array into string and kept on JSONObject. 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");

就是这样.

相关文章