[FEATURE] Сериализатор byte[] в Base64

This commit is contained in:
zaxar163 2019-05-31 09:49:05 +03:00
parent fe60d6b234
commit a0d6c5ad0e

View file

@ -6,6 +6,18 @@
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.Base64;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Locale;
@ -120,4 +132,23 @@ public static String[] parseCommand(CharSequence line) throws CommandException {
// Return result as array
return result.toArray(new String[0]);
}
@LauncherAPI
public static GsonBuilder newBuilder() {
return new GsonBuilder().registerTypeHierarchyAdapter(byte[].class,
ByteArrayToBase64TypeAdapter.INSTANCE);
}
private static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {
private static final ByteArrayToBase64TypeAdapter INSTANCE = new ByteArrayToBase64TypeAdapter();
private Base64.Decoder decoder = Base64.getUrlDecoder();
private Base64.Encoder encoder = Base64.getUrlEncoder();
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return decoder.decode(json.getAsString());
}
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(encoder.encodeToString(src));
}
}
}