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.
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With