0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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 Yes this is the java way to do it.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.