简体   繁体   中英

Java Parse Json Byte Array

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM