直接上代码:
public class ValidUtils {
public static <T> JSONObject inspect(T t, String requireParams) {
JSONObject jsonResult = new JSONObject();
jsonResult.put("code", CommonResultEnum.CHECK_VALID.code());
String jsonString = JSONObject.toJSONString(t);
JSONObject jsonObject = JSONObject.parseObject(jsonString);
String[] params = requireParams.split(",");
for (String param : params) {
if (jsonObject.getString(param) == null || jsonObject.getString(param).isEmpty()) {
jsonResult.put("code", CommonResultEnum.CHECK_VALID_ERROR.code());
jsonResult.put("msg", String.format(CommonResultEnum.CHECK_VALID_ERROR.message(), param));
break;
}
}
return jsonResult;
}
}
测试:
@Test
public void testValidUtils() {
User user = new User();
user.setUsername("张思睿");
user.setPassword("123456");
JSONObject jsonResult = ValidUtils.inspect(user, "username,password,age");
System.out.println(jsonResult.get("code") + ": " + jsonResult.get("msg"));
}
打印:
20201: age参数为空