I need to create JSON based on a blob from database. To get the blob image, I use the code below and after show in json array:
Statement s = connection.createStatement();
ResultSet r = s.executeQuery("select image from images");
while (r.next()) {
JSONObject obj = new JSONObject();
obj.put("img", r.getBlob("image"));
}
I to want return a JSON object for the each image according the image blob. How can I achieve it?
Binary data in JSON is usually best to be represented in a Base64-encoded form. You could use the standard Java SE provided DatatypeConverter#printBase64Binary()
method to Base64-encode a byte array.
byte[] imageBytes = resultSet.getBytes("image");
String imageBase64 = DatatypeConverter.printBase64Binary(imageBytes);
obj.put("img", imageBase64);
The other side has just to Base64-decode it. E.g. in Android, you could use the builtin android.util.Base64
API for this.
byte[] imageBytes = Base64.decode(imageBase64, Base64.DEFAULT);