Java Parse Json Byte Array

吃可爱长大的小学妹 提交于 2019-12-12 03:16:30

问题


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:


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.



来源:https://stackoverflow.com/questions/10403862/java-parse-json-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!