I tried to get my byte[]
value from JSONObject
using following code but I am not getting original byte[]
value.
JSONAr
For tests example(com.fasterxml.jackson used):
byte[] bytes = "pdf_report".getBytes("UTF-8");
Mockito.when(reportService.createPackageInvoice(Mockito.any(String.class))).thenReturn(bytes);
String jStr = new ObjectMapper().writeValueAsString(bytes).replaceAll("\\\"", ""); // return string with a '\"' escape...
mockMvc.perform(get("/api/getReport").param("someparam", "222"))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
...
.andExpect(jsonPath("$.content", is(jStr)))
;
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.
When inserting a byte array into a JSONObject the toString() method is invoked.
public static void main(String... args) throws JSONException{
JSONObject o = new JSONObject();
byte[] b = "hello".getBytes();
o.put("A", b);
System.out.println(o.get("A"));
}
Example output:
[B@1bd8c6e
so you have to store it in a way that you can parse the String into the original datatype.
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);