Search code examples
javaarrayspdfjersey

Put/get byte array value using JSONObject


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.


Solution

  • 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.