Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSON object with Bitmaps

I have an object which contains a few string members and a bitmap member.

The object is held in a map with a String key and the Object as the value.

I'm using the following code to convert the map:

String json = new Gson().toJson(aMap);

and then to extract the JSON map I use (passing the above JSON string):

Map<String, Object> aMap;
    Gson gson = new Gson();
    aMap = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() {}.getType());

This partially works but the bitmap stored in the object appears to corrupted? i.e. when I try to apply bitmap to an image view I get an exception.

I'm thinking I may need to separately convert the bitmap to a string for JSON but hoping theres a simpler solution, any ideas?

Thanks.

like image 472
GordonW Avatar asked Jun 13 '15 12:06

GordonW


People also ask

Can we convert JSONObject to string?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How to parse JSON object in Java?

First, we need to convert the JSON string into a JSON Object, using JSONObject class. Also, note that “pageInfo” is a JSON Object, so we use the getJSONObject method. Likewise, “posts” is a JSON Array, so we need to use the getJSONArray method.

How to represent null in JSON?

If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null . No braces, no brackets, no quotes.


1 Answers

This is actually simple :

 /*
 * This functions converts Bitmap picture to a string which can be
 * JSONified.
 * */
private String getStringFromBitmap(Bitmap bitmapPicture) {
   final int COMPRESSION_QUALITY = 100;
   String encodedImage;
   ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
   bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
   byteArrayBitmapStream);
   byte[] b = byteArrayBitmapStream.toByteArray();
   encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
   return encodedImage;
 }

and vice versa:

    /*
    * This Function converts the String back to Bitmap
    * */
    private Bitmap getBitmapFromString(String stringPicture) {
       byte[] decodedString = Base64.decode(stringPicture, Base64.DEFAULT);
       Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
       return decodedByte;
    }

This is not mine, I took it from HERE.

like image 106
Remy Avatar answered Nov 08 '22 21:11

Remy