这是我用来递归转换地图中对象的字段的方法,准备好与MockHttpServletRequestBuilder
public static void objectToPostParams(final String key, final Object value, final Map<String, String> map) throws IllegalAccessException {
if ((value instanceof Number) || (value instanceof Enum) || (value instanceof String)) {
map.put(key, value.toString());
} else if (value instanceof Date) {
map.put(key, new SimpleDateFormat("yyyy-MM-dd HH:mm").format((Date) value));
} else if (value instanceof GenericDTO) {
final Map<String, Object> fieldsMap = ReflectionUtils.getFieldsMap((GenericDTO) value);
for (final Entry<String, Object> entry : fieldsMap.entrySet()) {
final StringBuilder sb = new StringBuilder();
if (!GenericValidator.isEmpty(key)) {
sb.append(key).append('.');
}
sb.append(entry.getKey());
objectToPostParams(sb.toString(), entry.getValue(), map);
}
} else if (value instanceof List) {
for (int i = 0; i < ((List) value).size(); i++) {
objectToPostParams(key + '[' + i + ']', ((List) value).get(i), map);
}
}
}
GenericDTO
是一个简单的类扩展Serializable
public interface GenericDTO extends Serializable {}
这是ReflectionUtils
课程
public final class ReflectionUtils {
public static List<Field> getAllFields(final List<Field> fields, final Class<?> type) {
if (type.getSuperclass() != null) {
getAllFields(fields, type.getSuperclass());
}
// if a field is overwritten in the child class, the one in the parent is removed
fields.addAll(Arrays.asList(type.getDeclaredFields()).stream().map(field -> {
final Iterator<Field> iterator = fields.iterator();
while(iterator.hasNext()){
final Field fieldTmp = iterator.next();
if (fieldTmp.getName().equals(field.getName())) {
iterator.remove();
break;
}
}
return field;
}).collect(Collectors.toList()));
return fields;
}
public static Map<String, Object> getFieldsMap(final GenericDTO genericDTO) throws IllegalAccessException {
final Map<String, Object> map = new HashMap<>();
final List<Field> fields = new ArrayList<>();
getAllFields(fields, genericDTO.getClass());
for (final Field field : fields) {
final boolean isFieldAccessible = field.isAccessible();
field.setAccessible(true);
map.put(field.getName(), field.get(genericDTO));
field.setAccessible(isFieldAccessible);
}
return map;
}
}
你可以像这样使用它
final MockHttpServletRequestBuilder post = post("/");
final Map<String, String> map = new TreeMap<>();
objectToPostParams("", genericDTO, map);
for (final Entry<String, String> entry : map.entrySet()) {
post.param(entry.getKey(), entry.getValue());
}
我没有对它进行广泛的测试,但它似乎有效。