samedi 28 février 2015

Spring 4 Converters

I'm writing a webserivce using Spring 4. I have a problem with data binding. I've got 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 exception. I'm sending an object in json. In service I binding properties of received map to entity. All is ok if the properties are primitive. But If I have a custom pojo I have that exception.


I wrote two classes:



public class ArrayListToSetConverter implements Converter<ArrayList, Set>{

public Set convert(ArrayList source) {
Set set = new HashSet();
set.addAll(source);
return set;
}

}


and I'm trying to do it more generic with this class:



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;
}
}


I add line in @Configuration class:



@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;
}


But when I add a breakpoint in StringToAbstractEntityConverter app doens't stop in it. So it doesn't use this class...


I want to convert id from client to Object...


I will be very grateful if someone could help me with this :)


Best regards, Matt.


Aucun commentaire:

Enregistrer un commentaire