【发布时间】:2015-05-01 12:37:25
【问题描述】:
我正在使用 Spring 4 编写网络服务。我遇到了数据绑定问题。我有
org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.util.Set' for property 'groups'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [pl.tt.springtpl.models.Group] for property 'groups[0]': no matching editors or conversion strategy found 异常。我在 json 中发送一个对象。在服务中,我将接收到的映射的属性绑定到实体。如果属性是原始的,一切都很好。但是,如果我有一个自定义 pojo,我就有这个例外。
我写了两个类:
public class ArrayListToSetConverter implements Converter<ArrayList, Set>{
public Set convert(ArrayList source) {
Set set = new HashSet();
set.addAll(source);
return set;
}
}
我正在尝试使用此类更通用:
public class StringToAbstractEntityConverter implements ConditionalGenericConverter{
public Set<ConvertiblePair> getConvertibleTypes() {
ConvertiblePair cp = new ConvertiblePair(String.class, SimpleAbstractEntity.class);
Set<ConvertiblePair> set = new HashSet<ConvertiblePair>();
set.add(cp);
return set;
}
public Object convert(Object o, TypeDescriptor td, TypeDescriptor td1) {
Object w = td.getClass();
return o;
}
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
if(sourceType.getObjectType() == String.class && targetType.isAssignableTo(TypeDescriptor.valueOf(SimpleAbstractEntity.class))){
String idAsTxt = (String)sourceType.getSource();
long id = Long.valueOf(idAsTxt);
}
return true;
}
}
我在@Configuration 类中添加一行:
@Override
public FormattingConversionService mvcConversionService() {
FormattingConversionService bean = super.mvcConversionService(); //To change body of generated methods, choose Tools | Templates.
bean.addConverter(new StringToAbstractEntityConverter());
bean.addConverter(new ArrayListToSetConverter());
return bean;
}
但是当我在 StringToAbstractEntityConverter 应用程序中添加断点时,它并没有停止。所以它不使用这个类...
我想将 id 从客户端转换为对象...
如果有人可以帮助我,我将非常感激:)
最好的问候, 马特。
【问题讨论】:
标签: json spring spring-mvc data-binding spring-4