blob: a336e97283b936b5d7df8de24b336ac3742970f8 [file] [log] [blame]
Stuart McCullochf3173222012-06-07 21:57:32 +00001package aQute.lib.json;
2
3import java.io.*;
4import java.lang.reflect.*;
5import java.util.*;
6
7import aQute.lib.base64.*;
Stuart McCulloch55fbda52012-08-02 13:26:25 +00008import aQute.lib.hex.*;
Stuart McCullochf3173222012-06-07 21:57:32 +00009
10public class ByteArrayHandler extends Handler {
11
Stuart McCulloch4482c702012-06-15 13:27:53 +000012 @Override
13 void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception {
Stuart McCulloch55fbda52012-08-02 13:26:25 +000014 if ( app.codec.isHex())
15 StringHandler.string(app, Hex.toHexString((byte[]) object));
16 else
17 StringHandler.string(app, Base64.encodeBase64((byte[]) object));
Stuart McCullochf3173222012-06-07 21:57:32 +000018 }
19
Stuart McCulloch4482c702012-06-15 13:27:53 +000020 @Override
21 Object decodeArray(Decoder r) throws Exception {
Stuart McCullochf3173222012-06-07 21:57:32 +000022 ByteArrayOutputStream out = new ByteArrayOutputStream();
23
24 ArrayList<Object> list = new ArrayList<Object>();
25 r.codec.parseArray(list, Byte.class, r);
26 for (Object b : list) {
27 out.write(((Byte) b).byteValue());
28 }
29 return out.toByteArray();
30 }
31
Stuart McCulloch4482c702012-06-15 13:27:53 +000032 @Override
Stuart McCulloch55fbda52012-08-02 13:26:25 +000033 Object decode(Decoder dec, String s) throws Exception {
34 if ( dec.codec.isHex())
35 return Hex.toByteArray(s);
Stuart McCulloch2929e2d2012-08-07 10:57:21 +000036 return Base64.decodeBase64(s);
Stuart McCullochf3173222012-06-07 21:57:32 +000037 }
38}