How to convert JSONObject directly to byteArray without intermediate toString? - android

I have a JSONObject returned from a library. Sometimes the JSONObjects are too big and they cause an exception when applying toString to the JSONObject before applying getBytes to convert it to a byteArray. How do I convert JSONObject to ByteArray directly?

Try this code
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
Json.createWriter(byteArray).write(jsonObject);
byte[] data = stream.toByteArray()

Sample:
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
obj.put("nickname",null);
Your solution :
obj.toString().getBytes(theCharset);

Related

jackson ObjectMapper is adding an illegal character to base64 img string field on writeValueAsString

I am trying to send an object with an image converted to a base64 string, but when I convert that object to a json string to send it, multiple "\n" characters are added to that string which makes it invalid when it reaches the server.
Converting bitmap to a valid base64 (I checked if its valid)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
base64Str = Base64.encodeToString(outputStream.toByteArray(),
Base64.DEFAULT);
Creating the request and setting the base64 string to be sent to the backed
ObjectMapper mapper = new ObjectMapper();
Request = new Request();
payload.setData(base64);
on writeValueAsString a "/n" is added at the end of the base64 value which makes it invalid
String reqBody = "";
try {
reqBody = mapper.writeValueAsString(payload);
}
catch (Exception ex) {
}
a part of the valid base 64 before converting to json
"Kz7cruI+8gLNZRgnnKihQFDNt42sGaQlWMhVt2fLG9Q20NwpIx/
J0OWdOM4cso8tlZ3skldNWau0mmt7XT1P2/mcH
aWk15dFJrm+53Xndu7aP/9k="
a part of the valid base 64 after converting to json (notice the inclusion of '\n')
"Kz7cruI+8gLNZ\nRgnnKihQFDNt42sGaQlWMhVt2fLG9Q20NwpIx
/J0OWdOM4cso8tlZ3skldNWau0mmt7XT1P2/mcH\naWk15dFJrm+53Xndu7aP/9k=\n"
Found the issue, the new line character "\n" is added on encodeToString by default, to add a wrap effect. Just replace Base64.DEFAULT with Base64.NO_WRAP to remove it in the encoded string.

convert a string got from Jsonobject to Byte[];

I am transmitting a PDF in Bytearray from WEB API,
I am getting the response as follows
{"document":"JVBERi0xLjMNCiXi48\/TDQoNCjEgMCBvYmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL091dGxpbmVzIDIgMCBSDQovUGFnZXMgMyAwIFINCj4+DQplbmRvYmoNCg0KMiAwIG9iag0KPDwNCi9UeXBlIC9PdXRsaW5lcw0KL0NvdW50IDANCj4+DQplbmRvYmoNCg0KMyAwIG9iag0KPDwNCi9UeXBlIC"}
I want to convert that string to Byte array[] for rendering the PDF;
Please Help me with problem;
Try this
String json = "{\"document\":\"JVBERi0xLjMNCiXi48\/TDQoNCjEgMCBvYmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL091dGxpbmVzIDIgMCBSDQovUGFnZXMgMyAwIFINCj4+DQplbmRvYmoNCg0KMiAwIG9iag0KPDwNCi9UeXBlIC9PdXRsaW5lcw0KL0NvdW50IDANCj4+DQplbmRvYmoNCg0KMyAwIG9iag0KPDwNCi9UeXBlIC\"}";
JSONObject json_object = new JSONObject(json);
byte[] b = json_object.getString("document").getBytes();
//or
byte[] b = json_object.getString("document").getBytes(Charset.forName("UTF-8"));
As simple as :
byte[] byte = yourstring.getBytes();
byte[] byte = yourstring.getBytes(Charset.forName("UTF-8"));
String data = "sample text";
byte[] b = data.getBytes();
Use getBytes() method in string
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#getBytes()
I was able to get the Bytearray from JSON using
pdfbytes = Base64.decode(response.getString("document"), Base64.DEFAULT) ;

convert byte[] from json in android

how to get byte[] from json using webservice
My json format is given below:
[{"imgLogo":[255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,219,0,132,0,
9,6,7,20,19,18,20,20,19,20,21,22,20,22,20,21,24,22,21,21,20,20,20,20,20,
24,21,20,22,24,20,20,20,23,24,28,40,32,24,26,37,28,20,
21,33,49,33,37,41,43,46,46,46,23,31,51,56,51,44,55,40,45,46,43,1,10,10,10
,14,13,14,27,16,16,26,44,36,28,36,44,44,44,44,44,44,44,44,44,44,44,44,
44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,
44,44,44,44,44,44,44,44,44,44,44,44,44,44,44,255,192,0,17,8,0,194,1,3,3....]}]
I'm using this following code to get json value like this :
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String imagestring = jsonChildNode.getString("imgLogo");
Now, I'm getting above byte[] value as string. then how can I convert this string to byte[]
first create a String containing your data and then
byte[] data = Base64.decode(iconString, Base64.DEFAULT);
now you have byte array containing your bitmap.
Use this getBytes method :
byte[] bytes = imagestring .getBytes("UTF-8");

Send image within Json to a webservice in Android

I want to send a json object from my android device to the server (in post).
In my json object, I need to add an image in Base64. I cannot use to String to convert my image to Base64 because a String is too short to contain a Base64 encoded file.
I must use a BytesArray.
How to send something like that to a JSON webservice ?
{
"emergency":"gsjqsbl",
"cod_valid":"O",
"image":{
"content":"/9j/4AAQSkZJRg ## MY VERY VERY VERY VERY VERY VERY VERY LONG IMAGE IN BASE64 ## BWNn+SV5H8KQADnn9ysrKA1EVX+lNDkSJ8ai8UADCLoAR3TWVlHT95AVvcfwCvD4Hq1joP5NX3Ciat7zyP4VlZW9bnl1sf//Z",
"content_type":"image/jpg"
},
"indoor":"yes",
"access_conditional":"text",
"geo_shape":{
"type":"Point",
"coordinates":[
2.0202024,
45.799005
]
},
"lastupdate":"",
"ref_fr_sdis91":"",
"name":"TEST IN UPPERCASE WITH SPECIAL CHARACTERS ;/*-é#$~æ€",
"geo_point_2d":"45.799005,2.0202024",
"source":"soures",
"objectid":"",
"aed_location":"Spopopo"
}
I really cannot use String.
Thanks
EDIT : What i've done yet :
//output stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//write text
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write("json start { blabla: value");
//Write image
AssetManager assetManager = context.getAssets();
InputStream istr;
Bitmap bitmap = null;
try {
istr = assetManager.open("pictures/defib12.jpg");
bitmap = BitmapFactory.decodeStream(istr);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
outputStream.write(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
//write text
OutputStreamWriter outputStreamWriter2 = new OutputStreamWriter(outputStream);
bufferedWriter = new BufferedWriter(outputStreamWriter2);
bufferedWriter.write("json end }");
HttpResponse response = restClient.executePostRequest(pushUrl, outputStream);
And :
public HttpResponse executePostRequest(String url, ByteArrayOutputStream outputStream) throws IOException {
LogWrapper.debug(DmaRestClient.class, "New HttpPost request: " + url);
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(outputStream.toByteArray()));
request.setHeader("Content-Type", "application/json");
return client.execute(request);
}
You should use a lib to do that. Check Genson, it provides two mechanisms to ser/de binary content: using the classic base64 encoded strings (but in your case it looks like it won't work) or ser/de as an array of ints. Note that you will have to use the same mechanism on the server side - but it could be another library that support this kind of format.
With Genson you would create classes to represent your json and image.content value would be the byte array. To enable this option in Genson:
Genson genson = new GensonBuilder().useByteAsInt(true).create();
genson.serialize(yourObject, theOutputStream);
If you want to do it by hand without using any lib you still can (but it is a bad practice...) use the same trick => Ser/de the byte array as an int array.

Base64 decoding of JSONObject in Android 2.1

I need to decode JSONObject in Android 2.1 with Base64.I know that Base64 class supports Android 2.2+,that's why I include the source code in my project.So I need to do something like that :
JSONObject clientHash = new JSONObject();
byte[] tmpSecData = Base64.decode(clientHash.getJSONObject("client_auth_hash"));
Any suggestions how to do that or is it possible?
Lets try it,
Convert the clientHash.getJSONObject("client_auth_hash") in String then byteArray,
then use,
byte temp[];
Base64 b = new Base64();
String jsonString = clientHash.getJSONObject("client_auth_hash").toString();
temp = b.decode(jsonString.getBytes());
then use your temp byte[].
Hope this will help you. If its work then inform me. Thanx.

Categories

Resources