From 5f086bd47a462265b568cddd77f9af1f6a06633f Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Thu, 16 Jan 2020 12:15:36 +0100 Subject: Deserialize Strings to UTF-8 byte[] --- .../taskmanager/util/ByteArrayDeserializer.java | 31 ++++++++++++++++++++++ .../java/org/openslx/taskmanager/util/Util.java | 5 +++- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 daemon/src/main/java/org/openslx/taskmanager/util/ByteArrayDeserializer.java (limited to 'daemon') diff --git a/daemon/src/main/java/org/openslx/taskmanager/util/ByteArrayDeserializer.java b/daemon/src/main/java/org/openslx/taskmanager/util/ByteArrayDeserializer.java new file mode 100644 index 0000000..bb2631f --- /dev/null +++ b/daemon/src/main/java/org/openslx/taskmanager/util/ByteArrayDeserializer.java @@ -0,0 +1,31 @@ +package org.openslx.taskmanager.util; + +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; + +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +public class ByteArrayDeserializer implements JsonDeserializer +{ + + @Override + public byte[] deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context ) throws JsonParseException + { + if ( json.isJsonArray() ) { + JsonArray ja = json.getAsJsonArray(); + int len = ja.size(); + byte[] ba = new byte[ len ]; + int i = 0; + for ( JsonElement el : ja ) { + ba[i++] = el.getAsByte(); + } + return ba; + } + return json.getAsString().getBytes( StandardCharsets.UTF_8 ); + } + +} diff --git a/daemon/src/main/java/org/openslx/taskmanager/util/Util.java b/daemon/src/main/java/org/openslx/taskmanager/util/Util.java index 361c0e5..92602ff 100644 --- a/daemon/src/main/java/org/openslx/taskmanager/util/Util.java +++ b/daemon/src/main/java/org/openslx/taskmanager/util/Util.java @@ -18,7 +18,10 @@ public class Util */ public static Gson explicitGsonInstance() { - return gsonBuilder.excludeFieldsWithoutExposeAnnotation().create(); + return gsonBuilder + .excludeFieldsWithoutExposeAnnotation() + .registerTypeAdapter( byte[].class, new ByteArrayDeserializer() ) + .create(); } public static int parseInt(String str, int def) -- cgit v1.2.3-55-g7522