Reputation: 177
I'm receiving a JSON object that has a byte array in it in a string format because of limitations of my system. It's only for testing something.
I get the string in question "[ 1, 2, 3, 4]" for example in android and want to transform it so I end up with byte[] data = [ 1, 2, 3, 4] .
Using getBytes obviously doesn't return what I'm looking for and I'm kinda clueless as to what can be done here. Help would be greatly appreciated!
Edit : I just parsed the string to get the each integer in an array of ints. Is there a way to put that into a byte array easily?
Thanks
Upvotes: 0
Views: 169
Reputation: 59
Try this:
private static byte[] doConvert(String inStr) {
String opStr = inStr.substring(1);
opStr = opStr.substring(0, opStr.length()-1);
int val;
String[] arr = opStr.split("[,]");
byte[] retVal = new byte[arr.length];
for (int i=0; i<arr.length; i++) {
opStr = arr[i].trim();
try {
val = Integer.parseInt(opStr);
} catch (Exception e) {
System.out.println("bad input at item #"+i+": "+opStr);
return null;
}
if (val > 255) {
System.out.println("bad input value at item #"+i+": "+val+" > 255");
return null;
}
retVal[i] = (byte) val;
}
return retVal;
}
Upvotes: 2