Skip to content

Commit f05dfad

Browse files
feat: add smart type conversion for Object[] parameters (#44)
1 parent b57bef6 commit f05dfad

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

src/main/java/org/casbin/CommandExecutor.java

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ public CommandExecutor(NewEnforcer enforcer, String inputMethodName, String[] in
3434
*/
3535
public static String convertToJson(String input) {
3636
input = input.trim();
37-
// Handle the simple format {key: value}
3837
if (!input.contains("\"")) {
3938
input = input.substring(1, input.length() - 1).trim();
4039
StringBuilder jsonBuilder = new StringBuilder("{");
@@ -83,7 +82,9 @@ public String outputResult() throws InvocationTargetException, IllegalAccessExce
8382
convertedParams[i] = Integer.valueOf(inputVal[i]);
8483
} else if(genericParameterTypes[i] == String.class) {
8584
convertedParams[i] = inputVal[i];
86-
} else if(genericParameterTypes[i] == Object[].class || genericParameterTypes[i] == String[].class) {
85+
} else if(genericParameterTypes[i] == Object[].class) {
86+
convertedParams[i] = smartConvertValue(Arrays.copyOfRange(inputVal, i, inputVal.length));
87+
} else if(genericParameterTypes[i] == String[].class) {
8788
convertedParams[i] = Arrays.copyOfRange(inputVal, i, inputVal.length);
8889
} else if (genericParameterTypes[i] == String[][].class) {
8990
String[] arr = Arrays.copyOfRange(inputVal, i, inputVal.length);
@@ -148,4 +149,37 @@ public String outputResult() throws InvocationTargetException, IllegalAccessExce
148149
ObjectMapper mapper = new ObjectMapper();
149150
return mapper.writeValueAsString(responseBody);
150151
}
152+
153+
private Object smartConvertValue(Object value) {
154+
if (value instanceof String[]) {
155+
String[] values = (String[]) value;
156+
Object[] convertedArray = new Object[values.length];
157+
for (int i = 0; i < values.length; i++) {
158+
convertedArray[i] = smartConvertValue(values[i]);
159+
}
160+
return convertedArray;
161+
}
162+
163+
String strValue = ((String) value).trim();
164+
165+
if (strValue.startsWith("\"") && strValue.endsWith("\"")) {
166+
return strValue.substring(1, strValue.length() - 1);
167+
}
168+
169+
if (strValue.matches("-?\\d+")) {
170+
return Integer.valueOf(strValue);
171+
}
172+
173+
if (strValue.matches("-?\\d*\\.\\d+")) {
174+
return Double.valueOf(strValue);
175+
}
176+
177+
if ("true".equalsIgnoreCase(strValue)) {
178+
return Boolean.TRUE;
179+
} else if ("false".equalsIgnoreCase(strValue)) {
180+
return Boolean.FALSE;
181+
}
182+
183+
return strValue;
184+
}
151185
}

0 commit comments

Comments
 (0)