From 37f4fef730a59fd5230b90e60039b05ed5e4d88b Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Wed, 17 Jul 2019 12:05:34 -0400 Subject: Convert double to int when decoding via gson Refactored MapDoubleAdapterFactory, extracting DoubleConverter to be used by code needing to convert Double to Integer/Long after being decoded by GSON. Enhanced StandardCoder to automatically use the above converter if the desired class is a generic Object. Change-Id: I1d4e83910de41ceda383f257bfea706db2b8fbbe Issue-ID: POLICY-1919 Signed-off-by: Jim Hahn --- .../policy/common/utils/coder/StandardCoder.java | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'utils/src/main') diff --git a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java index 1c65be82..80eddb86 100644 --- a/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java +++ b/utils/src/main/java/org/onap/policy/common/utils/coder/StandardCoder.java @@ -38,6 +38,7 @@ import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.nio.charset.StandardCharsets; +import org.onap.policy.common.gson.DoubleConverter; import org.onap.policy.common.gson.MapDoubleAdapterFactory; /** @@ -238,7 +239,7 @@ public class StandardCoder implements Coder { * @return the object represented by the given json string */ protected T fromJson(String json, Class clazz) { - return GSON.fromJson(json, clazz); + return convertFromDouble(clazz, GSON.fromJson(json, clazz)); } /** @@ -249,7 +250,24 @@ public class StandardCoder implements Coder { * @return the object represented by the given json string */ protected T fromJson(Reader source, Class clazz) { - return GSON.fromJson(source, clazz); + return convertFromDouble(clazz, GSON.fromJson(source, clazz)); + } + + /** + * Converts a value from Double to Integer/Long, walking the value's contents if it's + * a List/Map. Only applies if the specified class refers to the Object class. + * Otherwise, it leaves the value unchanged. + * + * @param clazz class of object to be decoded + * @param value value to be converted + * @return the converted value + */ + private T convertFromDouble(Class clazz, T value) { + if (clazz != Object.class) { + return value; + } + + return clazz.cast(DoubleConverter.convertFromDouble(value)); } /** -- cgit 1.2.3-korg