0

I have a Byte array being returned in my JSON.

JSON

[{"template":167,255,1,30,179,0,218,0,2,88,1,184,0], "template2":null, "template3":null, "Client_Id":1160739}]

In Java, how can I recover this byte array ?

I try return a String in JSON instead the byte array, but when I convert to byte, it will change the value that I need. Example, 167 is the value that I need because this is already the byte value, but if I try to convert 167 to byte, it will return another value, so I need recover it as byte value.

JAVA

ArrayList<JSONObject> vetor = ArrayJson(client);
byte[] template = (byte[])vetor.get(0).get("template");

I'm using the json.org/java repository to construct the json helper class.

Lucas_Santos
  • 4,638
  • 17
  • 71
  • 118

3 Answers3

1

The byte data type is good for 256 different numbers - yet, in java, when you use bytes, they are interpreted as signed two's complement numbers. This is most likely what happens to you. Note that the bit pattern is not changed, only the output changes.

You can recover the unsigned value in byte b with (b & 0xff)

Ingo
  • 36,037
  • 5
  • 53
  • 100
0

JSON has no concept of bytes, so what you have is an array of numbers. You can just iterate over them and build up a byte array by casting each of the numbers to byte.

Suppose you got your array of numbers into a int[] array using a JSON library of choice, simply do this:

int[] numbers = ...
byte[] bytes = new byte[numbers.length];
for (int i=0; i<numbers.length;i++) {
    bytes[i] = (byte)numbers[i];
}
Ridcully
  • 23,362
  • 7
  • 71
  • 86
0

Here is the code: The Classes are present in org.json package.

String jsonString = "{'template':[167,255,1,30,17,1,204,0,1,237,0,128,0] }";

JSONObject jObject = new JSONObject(jsonString);
JSONArray jArray = jObject.getJSONArray("template");
byte[] array = new byte[jArray.length()];

for(int i = 0; i < jArray.length(); i++) {
    array[i] = (byte)jArray.getInt(i);
}
Basant Singh
  • 5,736
  • 2
  • 28
  • 49
  • This will return negative values, like in `http://stackoverflow.com/questions/9609394/java-byte-array-contains-negative-numbers` I need e exactly the numbers that are returned is this array, because they are already the byte value – Lucas_Santos Oct 28 '13 at 14:26
  • 2
    @Lucas_Santos As I told in my answer: there is no way to get i.e. 204 out of a byte, unless you properly mask the value, as the conversion to int extends the sign. If you need 204 and are concerned about some "negative" numbers when printing, **don't use bytes**. – Ingo Oct 28 '13 at 14:51