From f27df01cccc6db4713124a816e631df57573b8c7 Mon Sep 17 00:00:00 2001 From: Justin Richer Date: Fri, 29 Jan 2016 16:42:40 -0500 Subject: [PATCH] encode empty arrays as nulls by default, leave old function as a backup closes #1011 --- .../main/java/org/mitre/util/JsonUtils.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/openid-connect-common/src/main/java/org/mitre/util/JsonUtils.java b/openid-connect-common/src/main/java/org/mitre/util/JsonUtils.java index 9019790dc..94fe23cc3 100644 --- a/openid-connect-common/src/main/java/org/mitre/util/JsonUtils.java +++ b/openid-connect-common/src/main/java/org/mitre/util/JsonUtils.java @@ -35,6 +35,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.Gson; import com.google.gson.JsonElement; +import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.google.gson.reflect.TypeToken; @@ -61,14 +62,30 @@ public class JsonUtils { private static Gson gson = new Gson(); /** - * Translate a set of strings to a JSON array + * Translate a set of strings to a JSON array, empty array returned as null * @param value * @return */ public static JsonElement getAsArray(Set value) { - return gson.toJsonTree(value, new TypeToken>(){}.getType()); + return getAsArray(value, false); } + + /** + * Translate a set of strings to a JSON array, optionally preserving the empty array. Otherwise (default) empty array is returned as null. + * @param value + * @param preserveEmpty + * @return + */ + public static JsonElement getAsArray(Set value, boolean preserveEmpty) { + if (!preserveEmpty && value != null && value.isEmpty()) { + // if we're not preserving empty arrays and the value is empty, return null + return JsonNull.INSTANCE; + } else { + return gson.toJsonTree(value, new TypeToken>(){}.getType()); + } + } + /** * Gets the value of the given member (expressed as integer seconds since epoch) as a Date */