35
35
import com .google .common .collect .Sets ;
36
36
import com .google .gson .Gson ;
37
37
import com .google .gson .JsonElement ;
38
+ import com .google .gson .JsonNull ;
38
39
import com .google .gson .JsonObject ;
39
40
import com .google .gson .JsonSyntaxException ;
40
41
import com .google .gson .reflect .TypeToken ;
@@ -61,14 +62,30 @@ public class JsonUtils {
61
62
private static Gson gson = new Gson ();
62
63
63
64
/**
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
65
66
* @param value
66
67
* @return
67
68
*/
68
69
public static JsonElement getAsArray (Set <String > value ) {
69
- return gson . toJsonTree (value , new TypeToken < Set < String >>(){}. getType () );
70
+ return getAsArray (value , false );
70
71
}
71
72
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
+
72
89
/**
73
90
* Gets the value of the given member (expressed as integer seconds since epoch) as a Date
74
91
*/
0 commit comments