[RESOLVIDO]Exception ao converter Date e List no vraptor

14 respostas
R
Esse é o json que eu to enviando:
{
    "rastreamentos": [
        {
            "models.visitante.Rastreamento":{ 
                "x": 10.5,
                "y": 45.9,
                "z": 45.9,
               "visitante": {
                   "id": 1
                },
               "dataHora": "2013-01-23 10:10:10"
            }
        },
       {
            "models.visitante.Rastreamento":{ 
                "x": 10.5,
                "y": 45.9,
                "z": 45.9,
               "visitante": {
                   "id": 1
                },
               "dataHora": "2013-01-23 10:10:10"
            }
        }
    ]
}
Esse é a action no meu controller:
@Consumes("application/json")
	@Post("/criar")
	public void criar(List<Rastreamento> rastreamentos) {
		dao.saveAll(rastreamentos);

		result.use(json()).withoutRoot().from(dao.list()).serialize();
	}
E dá esse erro:
com.thoughtworks.xstream.converters.ConversionException: Cannot parse date 2013-01-23 10:10:10
---- Debugging information ----
class               : java.util.ArrayList
required-type       : java.util.Date
line number         : -1
-------------------------------
	at com.thoughtworks.xstream.converters.basic.DateConverter.fromString(DateConverter.java:97)
	at com.thoughtworks.xstream.converters.SingleValueConverterWrapper.fromString(SingleValueConverterWrapper.java:41)
	at com.thoughtworks.xstream.converters.SingleValueConverterWrapper.unmarshal(SingleValueConverterWrapper.java:49)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
	at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshallField(AbstractReflectionConverter.java:246)
	at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:218)
	at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:162)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:60)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:71)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:68)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:60)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:71)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:68)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:82)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:76)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:60)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:137)
	at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:33)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:923)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:909)
	at com.thoughtworks.xstream.XStream.fromXML(XStream.java:861)
	at br.com.caelum.vraptor.deserialization.JsonDeserializer.deserialize(JsonDeserializer.java:62)
	at br.com.caelum.vraptor.interceptor.DeserializingInterceptor.intercept(DeserializingInterceptor.java:87)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor.intercept(ParametersInstantiatorInterceptor.java:93)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ExceptionHandlerInterceptor.intercept(ExceptionHandlerInterceptor.java:71)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.FlashInterceptor.intercept(FlashInterceptor.java:83)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.InstantiateInterceptor.intercept(InstantiateInterceptor.java:48)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ResourceLookupInterceptor.intercept(ResourceLookupInterceptor.java:69)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.EnhancedRequestExecution.execute(EnhancedRequestExecution.java:44)
	at br.com.caelum.vraptor.VRaptor$1.insideRequest(VRaptor.java:91)
	at br.com.caelum.vraptor.ioc.spring.SpringProvider.provideForRequest(SpringProvider.java:58)
	at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:88)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)

Ai eu vi que era necessário criar essa classe:

@Component
public class CustomJSONSerialization extends XStreamJSONSerialization {
 
    public CustomJSONSerialization(HttpServletResponse response, TypeNameExtractor extractor, ProxyInitializer initializer, XStreamBuilder builder) {
        super(response, extractor, initializer, builder);
    }
 
    @Override
    public XStream getXStream() {
        XStream xstream = super.getXStream();
        xstream.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", new String[0]));
        return xstream;
    }
 
}

Só que continua com o problema para fazer o parse da data, e mais uma pergunta como faço para não precisar utilizar o models.visitante.Rastreamento para referenciar a um tipo de objeto dentro do array json.

14 Respostas

Lucas_Cavalcanti

se vc registrou o dateConverter deveria funcionar… chegou a dar um clean no servidor?

R
Lucas Cavalcanti:
se vc registrou o dateConverter deveria funcionar... chegou a dar um clean no servidor?
Então Lucas,eu criei o converter e funcionou.
@Convert(Calendar.class) 
public class CalendarConverter implements Converter<Calendar> {

	public Calendar convert(String value, Class<? extends Calendar> arg1,
			ResourceBundle arg2) {
		Calendar calendar = Calendar.getInstance();
			try {
				Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value);
				calendar.setTime(date);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 return calendar; 
	}

}

Mas eu estou tendo problemas para receber a o List rastreamentos no método criar, quando eu realizo um post com esse json:

{
    "rastreamentos": [
        {
            "x": 30,
            "y": 31,
            "visitante": {
                "id": 2
            },
            "dataHora": "2013-05-10 10:10:10"
        },
        {
            "x": 30,
            "y": 31,
            "visitante": {
                "id": 2
            },
            "dataHora": "2013-05-10 10:10:10"
        }
    ]
}
Ele me retorna esse erro:
02:27:56,571 DEBUG [VRaptor             ] VRaptor received a new request
02:27:56,729 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor ResourceLookupInterceptor
02:27:56,730 DEBUG [DefaultResourceTranslator] trying to access /rastreamentos/criar
02:27:56,736 DEBUG [DefaultResourceTranslator] found resource [DefaultResourceMethod: RastreamentosController.criarRastreamentosController.criar(List)]
02:27:56,746 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor InstantiateInterceptor
02:27:56,907 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor ExceptionHandlerInterceptor
02:27:56,934 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor FlashInterceptor
02:27:57,016 DEBUG [ValidatorFactoryCreator] Initializing JSR303 factory for bean validation
02:27:57,024 DEBUG [JSR303ValidatorFactory] Initializing JSR303 Validator
02:27:57,034 DEBUG [MessageInterpolatorFactory] Initializing JSR303 MessageInterpolator
02:27:57,176 DEBUG [IogiParametersProvider] IogiParametersProvider is up
02:27:57,206 DEBUG [LazyInterceptorHandler] Invoking interceptor ParametersInstantiatorInterceptor
02:27:57,223 DEBUG [ParanamerNameProvider] Found parameter names with paranamer for RastreamentosController.criar(List) as [rastreamentos]
02:27:57,225 DEBUG [IogiParametersProvider] getParametersFor() called with parameters Parameters() and targets [Target(name=rastreamentos, type=interface java.util.List)].
02:27:57,227 DEBUG [ParametersInstantiatorInterceptor] Parameter values for [DefaultResourceMethod: RastreamentosController.criarRastreamentosController.criar(List)] are [null]
02:27:57,268 DEBUG [LazyInterceptorHandler] Invoking interceptor DeserializingInterceptor
02:27:57,644 DEBUG [ParanamerNameProvider] Found parameter names with paranamer for RastreamentosController.criar(List) as [rastreamentos]
02:27:57,645 DEBUG [XStreamConverters   ] registered Xstream converter forbr.com.caelum.vraptor.validator.MessageConverter
02:27:57,645 DEBUG [XStreamConverters   ] registered Xstream converter forbr.com.caelum.vraptor.serialization.xstream.XStreamConverters$NullConverter
Fev 01, 2013 2:27:57 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/EasyFair] threw exception
com.thoughtworks.xstream.converters.ConversionException: x : x
---- Debugging information ----
message             : x
cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : x
class               : java.util.ArrayList
required-type       : java.util.ArrayList
converter-type      : com.thoughtworks.xstream.converters.collections.CollectionConverter
line number         : -1
version             : null
-------------------------------
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:71)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.addCurrentElementToCollection(CollectionConverter.java:79)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:72)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:66)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
	at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1035)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1019)
	at com.thoughtworks.xstream.XStream.fromXML(XStream.java:904)
	at br.com.caelum.vraptor.deserialization.JsonDeserializer.deserialize(JsonDeserializer.java:62)
	at br.com.caelum.vraptor.interceptor.DeserializingInterceptor.intercept(DeserializingInterceptor.java:87)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor.intercept(ParametersInstantiatorInterceptor.java:93)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.FlashInterceptor.intercept(FlashInterceptor.java:83)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ExceptionHandlerInterceptor.intercept(ExceptionHandlerInterceptor.java:71)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.InstantiateInterceptor.intercept(InstantiateInterceptor.java:48)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ResourceLookupInterceptor.intercept(ResourceLookupInterceptor.java:69)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.EnhancedRequestExecution.execute(EnhancedRequestExecution.java:44)
	at br.com.caelum.vraptor.VRaptor$1.insideRequest(VRaptor.java:91)
	at br.com.caelum.vraptor.ioc.spring.SpringProvider.provideForRequest(SpringProvider.java:58)
	at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:88)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: x
	at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:56)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:55)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:79)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:74)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:45)
	at com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:70)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.addCurrentElementToCollection(CollectionConverter.java:79)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:72)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:66)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
	... 58 more
Eu achei estranho essa linha,que pelo que eu entendi parece que está passando o List rastreamentos como null:
02:27:57,227 DEBUG [ParametersInstantiatorInterceptor] Parameter values for [DefaultResourceMethod: RastreamentosController.criarRastreamentosController.criar(List)] are [null]
Essa é classe Rastreamento:
public class Rastreamento {
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="ID_RAS", nullable=false, unique=true)
	private  @Getter @Setter Long id;

	@Column(name="X_RAS")
	private  @Getter @Setter Double x;

	@Column(name="Y_RAS")
	private  @Getter @Setter Double y;

	@Column(name="Z_RAS")
	private  @Getter @Setter Double z;

	@Column(name="DT_HR_RAS")@Temporal(TemporalType.TIMESTAMP)
	private  @Getter @Setter Calendar dataHora;
	
	

	@ManyToOne
	@JoinColumn(name="ID_VIS", nullable=false, referencedColumnName="ID_VIS")
	private @Getter @Setter Visitante visitante;

	@Override
	public String toString() {
		return "Rastreamento [id=" + id + ", x=" + x + ", y=" + y + ", z=" + z
				+ ", dataHora=" + dataHora + ", visitante=" + visitante + "]";
	}

	
	
}
Caso eu tenha que escrever algum converter gostaria de saber como ele poderia ser,pois nesse caso eu teria que manipular essa lista de objetos do tipo Rastreamento.
Lucas_Cavalcanti

vixe… receber lista com json não funciona direito no XStream… tem até um plugin pra fazer isso com outra lib (Gson) que funciona melhor…


e na próxima versão do vraptor estará incluído.

R

Lucas Cavalcanti:
vixe… receber lista com json não funciona direito no XStream… tem até um plugin pra fazer isso com outra lib (Gson) que funciona melhor…


e na próxima versão do vraptor estará incluído.


Mas Lucas,pelo que eu entendi esses dois são para serialização ,e eu preciso deserializar. Você teria algum exemplo disso funcionando,pois eu já quebrei muito a cabeça com isso,e aqui no fórum têm outros exemplos,mas mesmo assim eu não consegui fazer serializar listas. Eu até olhei esse aqui: https://github.com/renanreismartins/vraptor-gson , mas tambem não funcionou.

Lucas_Cavalcanti

o formato que o xstream entende é algo parecido com:

{  
    "rastreamentos": [  
        {"br.com.pacote.Rastreamento": {  
            "x": 30,  
            "y": 31,  
            "visitante": {  
                "id": 2  
            },  
            "dataHora": "2013-05-10 10:10:10"  
        }},
       { "br.com.pacote.Rastreamento": { 
            "x": 30,  
            "y": 31,  
            "visitante": {  
                "id": 2  
            },  
            "dataHora": "2013-05-10 10:10:10"  
        }  }
    ]  
}
R

Mas como eu faço para não precisar do br.com.pacote.Rastreamento passando apenas {} dentro do array?

Lucas_Cavalcanti

implementa a deserialização usando outra lib :wink:

vc pode fazer uma específica pra rastreamento, vai ser mais fácil…

https://github.com/caelum/vraptor/blob/gson/vraptor-core/src/main/java/br/com/caelum/vraptor/deserialization/JsonDeserializer.java

R
Eu criei a classe JsonSerializar no projeto:
import static com.google.common.base.Preconditions.checkArgument;

import java.io.InputStream;
import java.lang.reflect.Method;

import br.com.caelum.vraptor.deserialization.Deserializer;
import br.com.caelum.vraptor.deserialization.Deserializes;
import br.com.caelum.vraptor.http.ParameterNameProvider;
import br.com.caelum.vraptor.interceptor.TypeNameExtractor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.serialization.xstream.VRaptorXStream;
import br.com.caelum.vraptor.serialization.xstream.XStreamBuilder;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

@Deserializes({"application/json","json"})
public class JsonDeserializer implements Deserializer {

	private final ParameterNameProvider provider;
	private final XStreamBuilder builder;
	private final TypeNameExtractor extractor;

	public JsonDeserializer(ParameterNameProvider provider,
			TypeNameExtractor extractor, XStreamBuilder builder) {
		this.provider = provider;
		this.extractor = extractor;
		this.builder = builder;
	}

	public Object[] deserialize(InputStream inputStream, ResourceMethod method) {
		Method javaMethod = method.getMethod();
		Class<?>[] types = javaMethod.getParameterTypes();
		checkArgument(
				types.length > 0,
				"Methods that consumes representations must receive just one argument: the root element");

		XStream xStream = getConfiguredXStream(javaMethod, types);

		Object[] params = new Object[types.length];

		chooseParam(types, params, xStream.fromXML(inputStream));

		return params;
	}

	/**
	 * Returns an xstream instance already configured.
	 */
	public XStream getConfiguredXStream(Method javaMethod, Class<?>[] types) {
		XStream xStream = getXStream();
		aliasParams(javaMethod, types, xStream);
		return builder.configure(xStream);
	}

	private void chooseParam(Class<?>[] types, Object[] params,
			Object deserialized) {
		for (int i = 0; i < types.length; i++) {
			if (types[i].isInstance(deserialized)) {
				params[i] = deserialized;
			}
		}
	}

	private void aliasParams(Method method, Class<?>[] types,
			XStream deserializer) {
		String[] names = provider.parameterNamesFor(method);
		for (int i = 0; i < names.length; i++) {
			deserializer.alias(names[i], types[i]);
		}
	}

	/**
	 * Extension point to configure your xstream instance.
	 * 
	 * @return the configured xstream instance
	 */
	protected XStream getXStream() {
		return new VRaptorXStream(extractor, getHierarchicalStreamDriver());
	}

	/**
	 * You can override this method for configuring Driver before serialization
	 */
	protected HierarchicalStreamDriver getHierarchicalStreamDriver() {
		return new JettisonMappedXmlDriver();
	}
	
	
}
Ai eu passei esse json:
{    
    "rastreamentos": [    
        {"br.com.pacote.Rastreamento": {    
            "x": 30,    
            "y": 31,    
            "visitante": {    
                "id": 2    
            },    
            "dataHora": "2013-05-10 10:10:10"    
        }},  
       { "br.com.pacote.Rastreamento": {   
            "x": 30,    
            "y": 31,    
            "visitante": {    
                "id": 2    
            },    
            "dataHora": "2013-05-10 10:10:10"    
        }  }  
    ]    
}
E deu esse erro:
11:34:22,777 DEBUG [VRaptor             ] VRaptor received a new request
11:34:22,781 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor ResourceLookupInterceptor
11:34:22,781 DEBUG [DefaultResourceTranslator] trying to access /rastreamentos/criar
11:34:22,782 DEBUG [DefaultResourceTranslator] found resource [DefaultResourceMethod: RastreamentosController.criarRastreamentosController.criar(List)]
11:34:22,785 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor ExceptionHandlerInterceptor
11:34:22,787 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor InstantiateInterceptor
11:34:22,813 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor FlashInterceptor
11:34:22,819 DEBUG [IogiParametersProvider] IogiParametersProvider is up
11:34:22,822 DEBUG [LazyInterceptorHandler] Invoking interceptor ParametersInstantiatorInterceptor
11:34:22,822 DEBUG [ParanamerNameProvider] Found parameter names with paranamer for RastreamentosController.criar(List) as [rastreamentos]
11:34:22,822 DEBUG [IogiParametersProvider] getParametersFor() called with parameters Parameters() and targets [Target(name=rastreamentos, type=interface java.util.List)].
11:34:22,822 DEBUG [ParametersInstantiatorInterceptor] Parameter values for [DefaultResourceMethod: RastreamentosController.criarRastreamentosController.criar(List)] are [null]
11:34:22,827 DEBUG [LazyInterceptorHandler] Invoking interceptor DeserializingInterceptor
11:34:22,832 DEBUG [ParanamerNameProvider] Found parameter names with paranamer for RastreamentosController.criar(List) as [rastreamentos]
11:34:22,832 DEBUG [XStreamConverters   ] registered Xstream converter forbr.com.caelum.vraptor.validator.MessageConverter
11:34:22,832 DEBUG [XStreamConverters   ] registered Xstream converter forbr.com.caelum.vraptor.serialization.xstream.XStreamConverters$NullConverter
Feb 01, 2013 11:34:22 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/EasyFair] threw exception
com.thoughtworks.xstream.converters.ConversionException: null : null
---- Debugging information ----
cause-exception     : java.lang.NullPointerException
cause-message       : null
class               : br.com.pacote.Rastreamento
required-type       : br.com.pacote.Rastreamento
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
line number         : -1
class[1]            : java.util.ArrayList
converter-type[1]   : com.thoughtworks.xstream.converters.collections.CollectionConverter
version             : null
-------------------------------
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:71)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.addCurrentElementToCollection(CollectionConverter.java:79)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:72)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:66)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:71)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.addCurrentElementToCollection(CollectionConverter.java:79)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:72)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:66)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
	at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1035)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1019)
	at com.thoughtworks.xstream.XStream.fromXML(XStream.java:904)
	at br.com.easyfair.util.converters.JsonDeserializer.deserialize(JsonDeserializer.java:45)
	at br.com.caelum.vraptor.interceptor.DeserializingInterceptor.intercept(DeserializingInterceptor.java:87)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor.intercept(ParametersInstantiatorInterceptor.java:93)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.FlashInterceptor.intercept(FlashInterceptor.java:83)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.InstantiateInterceptor.intercept(InstantiateInterceptor.java:48)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ExceptionHandlerInterceptor.intercept(ExceptionHandlerInterceptor.java:71)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ResourceLookupInterceptor.intercept(ResourceLookupInterceptor.java:69)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.EnhancedRequestExecution.execute(EnhancedRequestExecution.java:44)
	at br.com.caelum.vraptor.VRaptor$1.insideRequest(VRaptor.java:91)
	at br.com.caelum.vraptor.ioc.spring.SpringProvider.provideForRequest(SpringProvider.java:58)
	at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:88)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
	at br.com.caelum.vraptor.serialization.xstream.VRaptorClassMapper.shouldSerializeMember(VRaptorClassMapper.java:55)
	at com.thoughtworks.xstream.mapper.MapperWrapper.shouldSerializeMember(MapperWrapper.java:74)
	at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:297)
	at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:230)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
	... 66 more
Não funcionou,ai eu tentei com esse outro:
{    
    "rastreamentos": [    
       {    
            "x": 30,    
            "y": 31,    
            "visitante": {    
                "id": 2    
            },    
            "dataHora": "2013-05-10 10:10:10"    
        },  
       {    
            "x": 30,    
            "y": 31,    
            "visitante": {    
                "id": 2    
            },    
            "dataHora": "2013-05-10 10:10:10"    
        }
    ]    
}
E deu esse erro:
11:38:39,144 DEBUG [VRaptor             ] VRaptor received a new request
11:38:39,149 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor ResourceLookupInterceptor
11:38:39,149 DEBUG [DefaultResourceTranslator] trying to access /rastreamentos/criar
11:38:39,149 DEBUG [DefaultResourceTranslator] found resource [DefaultResourceMethod: RastreamentosController.criarRastreamentosController.criar(List)]
11:38:39,153 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor ExceptionHandlerInterceptor
11:38:39,154 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor InstantiateInterceptor
11:38:39,165 DEBUG [ToInstantiateInterceptorHandler] Invoking interceptor FlashInterceptor
11:38:39,170 DEBUG [IogiParametersProvider] IogiParametersProvider is up
11:38:39,173 DEBUG [LazyInterceptorHandler] Invoking interceptor ParametersInstantiatorInterceptor
11:38:39,173 DEBUG [ParanamerNameProvider] Found parameter names with paranamer for RastreamentosController.criar(List) as [rastreamentos]
11:38:39,173 DEBUG [IogiParametersProvider] getParametersFor() called with parameters Parameters() and targets [Target(name=rastreamentos, type=interface java.util.List)].
11:38:39,173 DEBUG [ParametersInstantiatorInterceptor] Parameter values for [DefaultResourceMethod: RastreamentosController.criarRastreamentosController.criar(List)] are [null]
11:38:39,178 DEBUG [LazyInterceptorHandler] Invoking interceptor DeserializingInterceptor
11:38:39,183 DEBUG [ParanamerNameProvider] Found parameter names with paranamer for RastreamentosController.criar(List) as [rastreamentos]
11:38:39,183 DEBUG [XStreamConverters   ] registered Xstream converter forbr.com.caelum.vraptor.validator.MessageConverter
11:38:39,183 DEBUG [XStreamConverters   ] registered Xstream converter forbr.com.caelum.vraptor.serialization.xstream.XStreamConverters$NullConverter
Feb 01, 2013 11:38:39 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [default] in context with path [/EasyFair] threw exception
com.thoughtworks.xstream.converters.ConversionException: x : x
---- Debugging information ----
message             : x
cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
cause-message       : x
class               : java.util.ArrayList
required-type       : java.util.ArrayList
converter-type      : com.thoughtworks.xstream.converters.collections.CollectionConverter
line number         : -1
version             : null
-------------------------------
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:79)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:71)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.addCurrentElementToCollection(CollectionConverter.java:79)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:72)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:66)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
	at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1035)
	at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1019)
	at com.thoughtworks.xstream.XStream.fromXML(XStream.java:904)
	at br.com.easyfair.util.converters.JsonDeserializer.deserialize(JsonDeserializer.java:45)
	at br.com.caelum.vraptor.interceptor.DeserializingInterceptor.intercept(DeserializingInterceptor.java:87)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ParametersInstantiatorInterceptor.intercept(ParametersInstantiatorInterceptor.java:93)
	at br.com.caelum.vraptor.core.LazyInterceptorHandler.execute(LazyInterceptorHandler.java:59)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.FlashInterceptor.intercept(FlashInterceptor.java:83)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:56)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.InstantiateInterceptor.intercept(InstantiateInterceptor.java:48)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ExceptionHandlerInterceptor.intercept(ExceptionHandlerInterceptor.java:71)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.interceptor.ResourceLookupInterceptor.intercept(ResourceLookupInterceptor.java:69)
	at br.com.caelum.vraptor.core.ToInstantiateInterceptorHandler.execute(ToInstantiateInterceptorHandler.java:54)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.next(DefaultInterceptorStack.java:54)
	at br.com.caelum.vraptor.core.EnhancedRequestExecution.execute(EnhancedRequestExecution.java:44)
	at br.com.caelum.vraptor.VRaptor$1.insideRequest(VRaptor.java:91)
	at br.com.caelum.vraptor.ioc.spring.SpringProvider.provideForRequest(SpringProvider.java:58)
	at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:88)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
	at java.lang.Thread.run(Thread.java:722)
Caused by: com.thoughtworks.xstream.mapper.CannotResolveClassException: x
	at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:56)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.DynamicProxyMapper.realClass(DynamicProxyMapper.java:55)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.PackageAliasingMapper.realClass(PackageAliasingMapper.java:88)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.ClassAliasingMapper.realClass(ClassAliasingMapper.java:79)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.ArrayMapper.realClass(ArrayMapper.java:74)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.MapperWrapper.realClass(MapperWrapper.java:30)
	at com.thoughtworks.xstream.mapper.CachingMapper.realClass(CachingMapper.java:45)
	at com.thoughtworks.xstream.core.util.HierarchicalStreams.readClassType(HierarchicalStreams.java:29)
	at com.thoughtworks.xstream.converters.collections.AbstractCollectionConverter.readItem(AbstractCollectionConverter.java:70)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.addCurrentElementToCollection(CollectionConverter.java:79)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:72)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.populateCollection(CollectionConverter.java:66)
	at com.thoughtworks.xstream.converters.collections.CollectionConverter.unmarshal(CollectionConverter.java:61)
	at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
	... 58 more
Lucas prq é tão complicado trabalhar com json list no vraptor,eu acho que vcs do projeto poderiam adicionar no cookbook do vraptor alguma implementação básica para resolver esse problema,que pelo que eu vi é corriqueira,e não há um padrão bem definido para resolver esse problema.
Lucas_Cavalcanti

é complicado de trabalhar com json list em qqer ambiente… não dá pra fazer uma solução muito genérica…

a idéia daquele deserializer era modificá-lo pra conseguir deserializar a sua classe…

dá uma olhadinha na api do Gson e veja se é fácil fazer isso.

em todo caso aceitamos contribuições e idéias pra resolver esse problema =)

R

Eu consegui resolver o meu problema,vou postar minha solução para quem tiver um problema parecido não quebre muito a cabeça:
1 - Primeiro eu adicionei no meu projeto vraptor-gson no meu projeto: https://github.com/renanreismartins/vraptor-gson

2 - Adicionei essa classe:

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.sql.Types;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.com.caelum.vraptor.core.Localization;
import br.com.caelum.vraptor.deserialization.Deserializer;
import br.com.caelum.vraptor.deserialization.Deserializes;
import br.com.caelum.vraptor.http.ParameterNameProvider;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caelum.vraptor.view.ResultException;
import br.com.models.visitante.Mapeamentos;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

@Deserializes({ "application/json", "json" })
public class GsonDeserialization implements Deserializer {

	private static final Logger logger = LoggerFactory
			.getLogger(GsonDeserialization.class);

	private final ParameterNameProvider paramNameProvider;

	private Localization localization;

	public GsonDeserialization(ParameterNameProvider paramNameProvider,
			Localization localization) {
		this.paramNameProvider = paramNameProvider;
		this.localization = localization;
	}

	@Override
	public Object[] deserialize(InputStream inputStream, ResourceMethod method) {
		Method jMethod = method.getMethod();
		Class<?>[] types = jMethod.getParameterTypes();
		if (types.length == 0) {
			throw new IllegalArgumentException(
					"Methods that consumes representations must receive just one argument");
		}

		Gson gson = getGson();
		Object[] params = new Object[types.length];
		String[] parameterNames = paramNameProvider.parameterNamesFor(jMethod);

		try {
			String content = getContentOfStream(inputStream);
			logger.debug("json retrieved: " + content);

			JsonParser parser = new JsonParser();
			JsonObject root = (JsonObject) parser.parse(content);

			for (int i = 0; i < types.length; i++) {
				String name = parameterNames[i];
				JsonElement node = root.get(name);
				if (node != null) {
					params[i] = gson.fromJson(node, types[i]);
				}
			}
		} catch (Exception e) {
			throw new ResultException("Unable to deserialize data", e);
		}

		return params;
	}

	protected Gson getGson() {

		String pattern = ((SimpleDateFormat) DateFormat.getDateInstance(
				DateFormat.MEDIUM, localization.getLocale()))
				.toLocalizedPattern();

		GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat(pattern);
		gsonBuilder.registerTypeAdapter(Mapeamentos.class, new MapeamentosDeserializer());
		
		return gsonBuilder.create();
	}

	private String getContentOfStream(InputStream input) throws IOException {
		StringBuilder content = new StringBuilder();

		byte[] buffer = new byte[1024];
		int readed = 0;
		while ((readed = input.read(buffer)) != -1) {
			content.append(new String(buffer, 0, readed));
		}

		return content.toString();
	}

}

Notem que nessa linha:

Eu registrei um adapter especifico para deserializar a lista de dados que vem no json.
Essa classe Mapeamentos é um wrapper para a minha lista de objetos:

import java.util.List;

public class Mapeamentos {
	
	private List<Mapeamento> mapeamentos;
        public void setMapeamentos(List<Mapeamento> mapeamentos){
             this.mapeamentos = mapeamentos;
        }

       public List<Mapeamento> getMapeamentos(){
            return mapeamentos;
       }
}

3 - E criei a classe MapeamentosDeserializer que é o adapter que foi registrado anteriormente para o wrapper que eu criei:

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import br.com.models.Mapeamento;
import br.com.models.Mapeamentos;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

public class MapeamentosDeserializer implements JsonDeserializer<Mapeamentos>{

	@Override
	public Mapeamentos deserialize(JsonElement json, Type typeOfT,
			JsonDeserializationContext context) throws JsonParseException {
			Mapeamentos mapeamentos = new Mapeamentos();
			
			List<Mapeamento> maps = new ArrayList<Mapeamento>();
			JsonArray jsonArray = json.getAsJsonArray();
			for (int i = 0; i < jsonArray.size(); i++) {
				JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
				Mapeamento mapeamento = new Mapeamento(jsonObject.get("x").getAsDouble(), jsonObject.get("y").getAsDouble(), jsonObject.get("dataHora").getAsString());
				maps.add(mapeamento);
			}
			mapeamentos.setMapeamentos(maps);
			
		return mapeamentos;
	}

}

5 - e no meu controller ao invés de passar um List mapeamentos como parâmetro para o método,eu passo como parametro o Wrapper que eu criei:

@Resource
@Path("/mapeamentos")
public class MapeamentosController {

	private final MapeamentoDao dao;
	private final Result result;

	public MapeamentosController(RastreamentoDao dao, Result result) {
		this.dao = dao;
		this.result = result;
	}

	@Consumes("application/json")
	@Post("/criar")
	public void criar(Mapeamentos mapeamentos) {
		dao.saveAll(mapeamentos.getMapeamentos());

		result.use(json()).withoutRoot().from(dao.list())
				.serialize();
	}

}

6 - e quando eu envio esse json via Post tudo funciona normalmente:

{
    "mapeamentos": [
        {
            "x": 1,
            "y": 1,
            "dataHora": "2013-10-10 10:10:10"
        },
        {
            "x": 1,
            "y": 1,
            "dataHora": "2013-10-10 10:10:10"
        }
    ]
}

Bem, recomendo para que quiser entender melhor o funcionamento desses códigos que faça um debug da execução do request. Espero ter ajudado que estiver passando pelo mesmo problema,e caso tenha alguma solução melhor,fico aguardando sugestões.

Lucas_Cavalcanti

parece boa a solução… talvez ela fique meio difícil de manter se vc for usar @consumes pra vários objetos.

R

Lucas ,você não acha que o gson deveria ser a lib padrão para deserialização no vraptor,já que ,pelo menos no meu ponto de vista, ela é mais simples de se utilizar do que o XStream quando o assunto é criar um deserializer json?

Lucas_Cavalcanti

Quando o VRaptor 3 foi criado não existia o GSon, por isso foi feito com XStream. Já tem um branch em que a gente está colocando a implementação do GSon de serializer e deserializer:
https://github.com/caelum/vraptor/tree/gson

só falta fazer o merge com a branch principal.

R

Bom saber,acho que vai facilitar muito a nossa vida.

Criado 28 de janeiro de 2013
Ultima resposta 17 de fev. de 2013
Respostas 14
Participantes 2