GUJ Discussões   :   últimos tópicos   |   categorias   |   GUJ Respostas

Passando JSON para a classe controller Java Vrator4

Tags: #<Tag:0x00007f3bdfac1cb0> #<Tag:0x00007f3bdfac1b48>

Estou tentando passar um Json via ajax para minha classe controller mas não sei bem ao certo como fazer isso, poderiam me dar umas dicas ?

Função ajax:

$( "#cadastrar-avaliacao" ).click(function() {
	 var dados = $( "#add-avalicao" ).serializeArray();
		$.ajax({
			url:"/guide10/pagina/save",
			type:"POST",
			data: dados,
			datatype: "json",
			seccess: function (data) {
				alert("deu certo");
			}
			
		});
		
	 
	 });

Metodo da classe controller:

@Consumes("application/json")
	@Post
	public void save (AvaliacaoModel avaliacao) {
		this.entityManager.persist(avaliacao);
		result.forwardTo(this).index();
		
		
	}

View Guides:

<div class="wrapper">
		<%@ include file="../../../resources/jsp/sidebar.html"%>
		<div id="content">
			<%@ include file="../../../resources/jsp/menusupeior.jsp"%>


			<div class="container-fluid ">
				<div class="row d-flex align-items-md-stretch">
					<div class="col-lg-6 col-md-6 ">
						<div class="card to-do ">
							<h2>Listando as Guides</h2>
							<form method="post" id="add-avalicao">
								<table class="table table-hover">
									<thead>
										<tr>
											<th scope="col">Guides</th>
											<th scope="col">Avaliação</th>

										</tr>
									</thead>
									<tbody>
											
										<c:forEach items="${guide }" varStatus="id" var="guide">
											<input type="hidden" name="avaliacao.usuarioPertencente.idUsuario[${id.count }]" value="${auxSession.usuario.idUsuario}">
											<input type="hidden" name="avaliacao.guide.idGuide[${id.count }]" value="${guide.idGuide}">
											<tr>
												<td> <input type="text" value="${guide.guide }" class="form-control-plaintext" readonly>   </td>

												<td><select name="avaliacao.status[${id.count }]">

														<option value="0">Selecione</option>

														<c:forEach items="${avalia}" var="status">


															<option value="${status}">${status}</option>

														</c:forEach>
												</select></td>
											</tr>

										</c:forEach>
									</tbody>
								</table>
								 <input
									type="button" value="Salvar Avaliações" id="cadastrar-avaliacao">
							</form>
						</div>
					</div>

				</div>
			</div>
		</div>

	</div>
	<%@ include file="../../../resources/scripttogle.html"%>














</body>
</html>

Desse jeito está dando erro?

@Lucas_Camara quando eu clico no botão da esse erro

jun 29, 2020 5:35:27 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [default] in context with path [/guide10] threw exception
br.com.caelum.vraptor.http.InvalidParameterException: Exception when trying to instantiate Target(name=avaliacao, type=class br.com.guide10.models.AvaliacaoModel)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator.handleException(VRaptorInstantiator.java:129)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator.handleException(VRaptorInstantiator.java:131)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator.instantiate(VRaptorInstantiator.java:123)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator.instantiate(VRaptorInstantiator.java:115)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator$Proxy$_$$_WeldClientProxy.instantiate(Unknown Source)
	at br.com.caelum.vraptor.http.iogi.IogiParametersProvider.instantiateOrAddError(IogiParametersProvider.java:87)
	at br.com.caelum.vraptor.http.iogi.IogiParametersProvider.instantiateParameters(IogiParametersProvider.java:80)
	at br.com.caelum.vraptor.http.iogi.IogiParametersProvider.getParametersFor(IogiParametersProvider.java:72)
	at br.com.caelum.vraptor.http.iogi.IogiParametersProvider$Proxy$_$$_WeldClientProxy.getParametersFor(Unknown Source)
	at br.com.caelum.vraptor.observer.ParametersInstantiator.getParametersForCurrentMethod(ParametersInstantiator.java:149)
	at br.com.caelum.vraptor.observer.ParametersInstantiator.instantiate(ParametersInstantiator.java:89)
	at sun.reflect.GeneratedMethodAccessor73.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:93)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:266)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:253)
	at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:232)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:169)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:165)
	at org.jboss.weld.event.ObserverNotifier.notifyObservers(ObserverNotifier.java:119)
	at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:112)
	at org.jboss.weld.event.EventImpl.fire(EventImpl.java:83)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.start(DefaultInterceptorStack.java:90)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack$Proxy$_$$_WeldClientProxy.start(Unknown Source)
	at br.com.caelum.vraptor.observer.RequestHandlerObserver.handle(RequestHandlerObserver.java:93)
	at sun.reflect.GeneratedMethodAccessor64.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:93)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:266)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:253)
	at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:232)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:169)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:165)
	at org.jboss.weld.event.ObserverNotifier.notifyObservers(ObserverNotifier.java:119)
	at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:112)
	at org.jboss.weld.event.EventImpl.fire(EventImpl.java:83)
	at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:123)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
	at br.com.caelum.iogi.reflection.NewObject$JavaSetter.settersOf(NewObject.java:118)
	at br.com.caelum.iogi.reflection.NewObject$Setter.settersIn(NewObject.java:67)
	at br.com.caelum.iogi.reflection.NewObject$Setter.access$000(NewObject.java:63)
	at br.com.caelum.iogi.reflection.NewObject.populateProperties(NewObject.java:51)
	at br.com.caelum.iogi.reflection.NewObject.valueWithPropertiesSet(NewObject.java:42)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator$VRaptorTypeConverter.setPropertiesAfterConversions(VRaptorInstantiator.java:193)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator$VRaptorTypeConverter.instantiate(VRaptorInstantiator.java:176)
	at br.com.caelum.iogi.MultiInstantiator.instantiate(MultiInstantiator.java:20)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator.instantiate(VRaptorInstantiator.java:121)
	at br.com.caelum.iogi.reflection.NewObject.setProperty(NewObject.java:58)
	at br.com.caelum.iogi.reflection.NewObject.populateProperties(NewObject.java:52)
	at br.com.caelum.iogi.reflection.NewObject.valueWithPropertiesSet(NewObject.java:42)
	at br.com.caelum.iogi.ObjectInstantiator.instantiate(ObjectInstantiator.java:35)
	at br.com.caelum.iogi.MultiInstantiator.instantiate(MultiInstantiator.java:20)
	at br.com.caelum.vraptor.http.iogi.VRaptorInstantiator.instantiate(VRaptorInstantiator.java:121)
	... 55 more

Manda o código da classe AvaliacaoModel.

@Lucas_Camara atributos, o restante da classe sãos os getters e setters

@Entity
@Table(name = "c_avaliacao")
public class AvaliacaoModel {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long idAvaliacao;

	@ManyToOne
	@JoinColumn(name = "idUsuario")
	private UsuarioModel usuarioPertencente;

	@OneToOne
	@JoinColumn(name = "idGuide")
	private ComposicaoModel guide;

	@Enumerated(EnumType.ORDINAL)
	private TpavaliaType status;

E como é o json recebido em dados nessa parte?

var dados = $( "#add-avalicao" ).serializeArray();

Então, eu sou iniciante com ajax jquery, basicamente minha função pega o formulário id=“add-avaliação” e passa todo pra dentro dessa variável dados, não sei se isso é o correto se a minha function ta errada.

Dependendo do formato do json recebido na variável dados vai acontecer erro ao criar a instância da classe AvaliacaoModel. Pois, para funcionar, o json deve ter o mesmo formato dos atributos da classe. Por isso pedi para vc executar o código para ver qual json está indo para essa variável dados. Dê um console.log(dados); e copie o json impresso no console do navegador e mande ele aqui pra gente ver.

De qualquer forma, não é recomendado que seja usada uma entidade mapeada com o banco para receber os dados no controller (camada REST). É melhor ter uma classe para receber os dados e montar a entidade dentro de uma classe de lógica.

Acredito que esteja aqui realmente o erro.

  1. 0: {name: “avaliacao.usuarioPertencente.idUsuario[1]”, value: “1”}
    2. 1: {name: “avaliacao.guide.idGuide[1]”, value: “1”}
    3. 2: {name: “avaliacao.status[1]”, value: “POSITIVO”}
    4. 3: {name: “avaliacao.usuarioPertencente.idUsuario[2]”, value: “1”}
    5. 4: {name: “avaliacao.guide.idGuide[2]”, value: “3”}
    6. 5: {name: “avaliacao.status[2]”, value: “POSITIVO”}
    7. 6: {name: “avaliacao.usuarioPertencente.idUsuario[3]”, value: “1”}
    8. 7: {name: “avaliacao.guide.idGuide[3]”, value: “4”}
    9. 8: {name: “avaliacao.status[3]”, value: “POSITIVO”}
    10. 9: {name: “avaliacao.usuarioPertencente.idUsuario[4]”, value: “1”}
    11. 10: {name: “avaliacao.guide.idGuide[4]”, value: “5”}
    12. 11: {name: “avaliacao.status[4]”, value: “POSITIVO”}
    13. 12: {name: “avaliacao.usuarioPertencente.idUsuario[5]”, value: “1”}
    14. 13: {name: “avaliacao.guide.idGuide[5]”, value: “6”}
    15. 14: {name: “avaliacao.status[5]”, value: “POSITIVO”}
    16. length: 15
    17. proto: Array(0)

Sim, esse formato de json não serve para instanciar a classe AvaliacaoModel. Deve ser algo assim:

{
  usuarioPertencente: {
    // atributos da classe "UsuarioModel"
  },
  guide: {
    // atributos da classe "ComposicaoModel"
  },
  status: "VALOR_VALIDO_ENUM" // algum valor válido do enum "TpavaliaType"
}
1 Curtida

@Lucas_Camara depois de muita luta eu consegui refazer o json acredito que da forma certa, no entanto acho que ta dando erro na hora de passar para o controller, ele mostra o seguinte erro, Tem ideia do que seja?

br.com.caelum.vraptor.view.ResultException: Unable to deserialize data
	at br.com.caelum.vraptor.serialization.gson.GsonDeserialization.deserialize(GsonDeserialization.java:153)
	at br.com.caelum.vraptor.serialization.gson.GsonDeserialization$Proxy$_$$_WeldClientProxy.deserialize(Unknown Source)
	at br.com.caelum.vraptor.observer.DeserializingObserver.deserializes(DeserializingObserver.java:96)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:93)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:266)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:253)
	at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:232)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:169)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:165)
	at org.jboss.weld.event.ObserverNotifier.notifyObservers(ObserverNotifier.java:119)
	at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:112)
	at org.jboss.weld.event.EventImpl.fire(EventImpl.java:83)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack.start(DefaultInterceptorStack.java:90)
	at br.com.caelum.vraptor.core.DefaultInterceptorStack$Proxy$_$$_WeldClientProxy.start(Unknown Source)
	at br.com.caelum.vraptor.observer.RequestHandlerObserver.handle(RequestHandlerObserver.java:93)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.jboss.weld.injection.MethodInjectionPoint.invokeOnInstanceWithSpecialValue(MethodInjectionPoint.java:93)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:266)
	at org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:253)
	at org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:232)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:169)
	at org.jboss.weld.event.ObserverNotifier.notifyObserver(ObserverNotifier.java:165)
	at org.jboss.weld.event.ObserverNotifier.notifyObservers(ObserverNotifier.java:119)
	at org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:112)
	at org.jboss.weld.event.EventImpl.fire(EventImpl.java:83)
	at br.com.caelum.vraptor.VRaptor.doFilter(VRaptor.java:123)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Unknown Source)
Caused by: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 36
	at com.google.gson.JsonParser.parse(JsonParser.java:65)
	at com.google.gson.JsonParser.parse(JsonParser.java:45)
	at br.com.caelum.vraptor.serialization.gson.GsonDeserialization.deserialize(GsonDeserialization.java:108)
	... 51 more
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 36
	at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1505)
	at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1386)
	at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:531)
	at com.google.gson.stream.JsonReader.peek(JsonReader.java:414)
	at com.google.gson.JsonParser.parse(JsonParser.java:60)
	... 53 more

a função ficou assim Ajax:

	$("#cadastrar-avaliacao").click(function() {
		var dados = {
			"avalicao[0].usuarioPertencente" : $("#idUsuario1").val(),
			"avalicao[0].guide" : $("#idGuide1").val(),
			"avalicao[0].status" : $("#status1").val(),
			"avalicao[1].usuarioPertencente" : $("#idUsuario2").val(),
			"avalicao[1].guide" : $("#idGuide2").val(),
			"avalicao[1].status" : $("#status2").val()

		};

		console.log(dados);

		$.ajax({
			url : "/guide10/pagina/save",
			type : "POST",
			data : dados,
			datatype : "json",
			contentType : "application/json;"
		});

	});

E o método do controller:

@Consumes("application/json")  
	@Post
	public void save (List<AvaliacaoModel> avaliacao) {
		
		
		
		this.entityManager.persist(avaliacao);
		result.forwardTo(this).index();
		
		
	}

Tenta assim:

var dados = {
	"avalicao[0].usuarioPertencente": {
		"id": $("#idUsuario1").val()
	},
	"avalicao[0].guide": {
		"id": $("#idGuide1").val()
	},
	"avalicao[0].status": $("#status1").val(),
	"avalicao[1].usuarioPertencente": {
		"id": $("#idUsuario2").val()
	},
	"avalicao[1].guide": {
		"id": $("#idGuide2").val()
	},
	"avalicao[1].status": $("#status2").val()
};

Verifique se o atributo de “usuarioPertencente” e “guide” é “id” mesmo.

//