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");
}
}
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");
before adding into JSONObject
like follwoing:
JSONObject jSONObject = new JSONObject();
jSONObject.put(JSONConstant.BYTE_ARRAY_LIST, bList);
it creates file i.e I can open pdf file and read its content.
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.
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.
Solution:
I added byte array value previously on JSONObject and stored as String. When I tried to get from JSONObject to my byte array it returned String not my original byte array. And did not get the original byte array even I use following:
byte[] bArray=jSONObject.getString(key).toString().getBytes();
Now,
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);
And the code from which I get back my original byte array:
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");
That's it.
This might be of help for those using Java 8. Make use of java.util.Base64
.
Encoding byte array to String :
String encodedString = java.util.Base64.getEncoder().encodeToString(byteArray);
JSONObject.put("encodedString",encodedString);
Decode byte array from String :
String encodedString = (String) JSONObject.get("encodedString");
byte[] byteArray = java.util.Base64.getDecoder().decode(encodedString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With