【问题标题】:Convert String to DTO in the validator of constraint在约束的验证器中将 String 转换为 DTO
【发布时间】: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 的显式构造函数呢?

标签: spring hibernate dto


【解决方案1】:

无法构造 model.RoleDTO 的实例(在 [Source: UNKNOWN; line: -1, column: -1] 的 START_ARRAY 标记之外]

此错误意味着您正在尝试将 JSONArray 反序列化为 RoleDto 对象。这是不可能的。

这里的rolesAsString 的值类似于"[{\"id\":5,\"name\":\"sad\"}]"

像这样使用ObjectMapperTypeReference..

mapper.readValue(rolesAsString, new TypeReference<List<RoleDTO>>() {
    });

【讨论】:

    猜你喜欢
    • 2013-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多