Skip to content

Commit f27df01

Browse files
committed
encode empty arrays as nulls by default, leave old function as a backup
closes mitreid-connect#1011
1 parent 61433cc commit f27df01

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

openid-connect-common/src/main/java/org/mitre/util/JsonUtils.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import com.google.common.collect.Sets;
3636
import com.google.gson.Gson;
3737
import com.google.gson.JsonElement;
38+
import com.google.gson.JsonNull;
3839
import com.google.gson.JsonObject;
3940
import com.google.gson.JsonSyntaxException;
4041
import com.google.gson.reflect.TypeToken;
@@ -61,14 +62,30 @@ public class JsonUtils {
6162
private static Gson gson = new Gson();
6263

6364
/**
64-
* Translate a set of strings to a JSON array
65+
* Translate a set of strings to a JSON array, empty array returned as null
6566
* @param value
6667
* @return
6768
*/
6869
public static JsonElement getAsArray(Set<String> value) {
69-
return gson.toJsonTree(value, new TypeToken<Set<String>>(){}.getType());
70+
return getAsArray(value, false);
7071
}
7172

73+
74+
/**
75+
* Translate a set of strings to a JSON array, optionally preserving the empty array. Otherwise (default) empty array is returned as null.
76+
* @param value
77+
* @param preserveEmpty
78+
* @return
79+
*/
80+
public static JsonElement getAsArray(Set<String> value, boolean preserveEmpty) {
81+
if (!preserveEmpty && value != null && value.isEmpty()) {
82+
// if we're not preserving empty arrays and the value is empty, return null
83+
return JsonNull.INSTANCE;
84+
} else {
85+
return gson.toJsonTree(value, new TypeToken<Set<String>>(){}.getType());
86+
}
87+
}
88+
7289
/**
7390
* Gets the value of the given member (expressed as integer seconds since epoch) as a Date
7491
*/

0 commit comments

Comments
 (0)