在约束验证器中将String转换为DTO

时间:2019-09-03 07:05:23

标签: spring hibernate dto

我在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() {
    }

1 个答案:

答案 0 :(得分:0)

  

无法构造model.RoleDTO的实例(位于START_ARRAY令牌的[来源:UNKNOWN;行:-1,列:-1]

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

这里的bdp具有类似> bdp(securities = "BL0739252 Corp", fields = "SPNR_LIST", verbose = T) ReferenceDataResponse = { securityData[] = { securityData = { security = "BL0739252 Corp" eidData[] = { } fieldExceptions[] = { } sequenceNumber = 0 fieldData = { SPNR_LIST[] = { SPNR_LIST = { Group Date = 2013-05-28 Sponsor = "Carlyle Group/The" } SPNR_LIST = { Group Date = 2013-02-04 Sponsor = "Carlyle Group/The" } } } } } } 的价值

rolesAsString"[{\"id\":5,\"name\":\"sad\"}]"一起使用。

ObjectMapper