【发布时间】:2020-01-06 01:25:05
【问题描述】:
我在 DTO 中有这个字段:
private List<RoleDTO> roles;
它有一个验证器:
public class InternalUserValidator implements ConstraintValidator<InternalUserConstraint, Object> {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
private String[] rolesAsString;
private List<RoleDTO> roles;
.
.
.
@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
//here i get as string, for example: RoleDTO{id=1, name='ADMIN'}
rolesAsString = BeanUtils.getArrayProperty(value, rolesFieldName);//should i use also getproperty again?
//then i try to convert to arraylist:
roles = (List<RoleDTO>) mapper.convertValue(rolesAsString, RoleDTO.class);
但它给了
无法构造
model.RoleDTO的实例(超出 START_ARRAY 令牌 在 [来源:未知;行:-1,列:-1]
所以,在调试的时候,我也试过这个:
(List<RoleDTO>) mapper.convertValue("{\"id\":5,\"name\":\"sad\"}", RoleDTO.class)
这次:
无法构造
model.RoleDTO的实例(尽管至少存在一个 Creator):没有字符串参数构造函数/工厂方法可以从字符串值反序列化 ('{"id":5,"name":"sad"}' ) 在 [来源:未知;行:-1,列:-1]
我能做什么?
这是RoleDTO:
public class RoleDTO implements Serializable {
private Long id;
private String name;
//getters setters
public RoleDTO() {
}
【问题讨论】:
-
那你为什么不添加一个带有你的 id 和 name 的显式构造函数呢?