forked from json-iterator/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBase64Support.java
More file actions
41 lines (38 loc) · 1.29 KB
/
Base64Support.java
File metadata and controls
41 lines (38 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.jsoniter.extra;
import com.jsoniter.JsonIterator;
import com.jsoniter.spi.Slice;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jsoniter.spi.Decoder;
import com.jsoniter.spi.Encoder;
import com.jsoniter.spi.JsonException;
import com.jsoniter.spi.JsoniterSpi;
import java.io.IOException;
/**
* byte[] <=> base64
*/
public class Base64Support {
private static boolean enabled;
public static synchronized void enable() {
if (enabled) {
throw new JsonException("Base64Support.enable can only be called once");
}
enabled = true;
JsoniterSpi.registerTypeDecoder(byte[].class, new Decoder() {
@Override
public Object decode(JsonIterator iter) throws IOException {
Slice slice = iter.readStringAsSlice();
return Base64.decodeFast(slice.data(), slice.head(), slice.tail());
}
});
JsoniterSpi.registerTypeEncoder(byte[].class, new Encoder() {
@Override
public void encode(Object obj, JsonStream stream) throws IOException {
byte[] bytes = (byte[]) obj;
stream.write('"');
Base64.encodeToBytes(bytes, stream);
stream.write('"');
}
});
}
}