Question

In our web application there is a tomcat 5.5 server which runs a servlet that created a document, either PDF or Word, and then sends it back as json with this structure:

{
  "status": "OK", // or "ERROR" if an error occurred
  "format": "application/pdf", // or "application/msword" if a Word document was generated
  "document": [...] // document content
}

The document key is created by first exporting the document as a byte[] and then calling toString() on it.

The whole json is managed, in the servlet, by using this library, and here you can see an example of response.

However, when the PHP script which calls the tomcat server receives the json string and runs it through json_decode(), it returns NULL as if the data was not valid json.

Did I make any obvious error in this algorithm I used? Or, more in general, how do you properly transmit binary data using JSON?

Was it helpful?

Solution

Answering myself 'cause I found a solution to this problem even if I am unsure about what caused it in the first place.

Anyway, I found out that if I do a base64 encoding of the binary data before sending it as json, the json object gets properly parsed by the PHP script, and doing a base64 decoding successfully recreates the original document created by the servlet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top