Lucas_Santos
Lucas_Santos

Reputation: 4740

Get Byte from JSON

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.

Upvotes: 1

Views: 3914

Answers (3)

Basant Singh
Basant Singh

Reputation: 5916

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);
}

Upvotes: 0

Ridcully
Ridcully

Reputation: 23665

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];
}

Upvotes: 0

Ingo
Ingo

Reputation: 36339

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)

Upvotes: 1

Related Questions