Im developing an Android application which are using an webservice to fetch an image that are going to be displayed in the application.

I'm using JSON as my format. The whole connection process works like a charm but i need help with parsing the response from the webservice request.

This is my result:

[255,12,87,183,232,34,64,121,182,23]

Of course this is not the real data, im just trying to explain how the data looks like when i receive it. So my question is, how do i parse this data into an byte array?

Here is my connection code this far:

HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
InputStream stream = responseEntity.getContent();
String string_result= convertStreamToString(stream);

This works great and the variable 'string_result' contains the data that was received. So if someone know how to simply parse this JSON String Containing An Byte Array i would appreciate some help.

share|improve this question

1 Answer

up vote 2 down vote accepted

Here is an example of parsing this array to byte[] using the irreplaceable GSON library:

String str = "[255,12,87,183,232,34,64,121,182,23]";
Gson gson = new Gson();
byte[] parsed = gson.fromJson(str, byte[].class);
for (byte b : parsed) {
    System.out.println(b);
}

This code outputs:

-1
12
87
-73
-24
34
64
121
-74
23

Note that the java byte is signed and thus you get the negative numbers.

share|improve this answer
So -1 12 87 -73 -24 34 64 121 -74 23 is basically the same thing as 255,12,87,183,232,34,64,121,182,23 – Parek May 1 '12 at 20:32
@Parek Yes this is the java way to do it. – Boris Strandjev May 1 '12 at 20:32
2  
@Parek By the way if I get you correctly what you need the byte array is for communicating blob item contents. However I would say that base64 encoding (en.wikipedia.org/wiki/Base64) will serve you better and will reduce the request size significantly. – Boris Strandjev May 1 '12 at 20:50

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.