blob: 957369fa1a9ed34405942c1301dcd99c3ade01c0 [file] [log] [blame]
Stuart McCullochbb014372012-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 McCullocha21b9e82012-08-02 13:26:25 +00008import aQute.lib.hex.*;
Stuart McCullochbb014372012-06-07 21:57:32 +00009
10public class ByteArrayHandler extends Handler {
11
Stuart McCulloch2286f232012-06-15 13:27:53 +000012 @Override
13 void encode(Encoder app, Object object, Map<Object,Type> visited) throws IOException, Exception {
Stuart McCullocha21b9e82012-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 McCullochbb014372012-06-07 21:57:32 +000018 }
19
Stuart McCulloch2286f232012-06-15 13:27:53 +000020 @Override
21 Object decodeArray(Decoder r) throws Exception {
Stuart McCullochbb014372012-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 McCulloch2286f232012-06-15 13:27:53 +000032 @Override
Stuart McCullocha21b9e82012-08-02 13:26:25 +000033 Object decode(Decoder dec, String s) throws Exception {
34 if ( dec.codec.isHex())
35 return Hex.toByteArray(s);
36 else
37 return Base64.decodeBase64(s);
Stuart McCullochbb014372012-06-07 21:57:32 +000038 }
39}