Why do I get this error when sending JSON from AJAX to JAVA SPRING MVC?

1

Good, two days ago I'm going crazy with this problem.

This object json sent as an example:

{"listado":
       [{"pos":0,"idfact":30,"idprod":1,"idremito":29,"cant":1,"descripadic":"","precio":55,"subtotal":55},{"pos":1,"idfact":30,"idprod":2,"idremito":29,"cant":2,"descripadic":"","precio":85,"subtotal":170},{"pos":2,"idfact":30,"idprod":4,"idremito":29,"cant":3,"descripadic":"","precio":63.5,"subtotal":190.5}]}

This is the AJAX code used

$.ajax({
            "type":"post",
            "url":"agregarRenglonesFactura",
            "contentType": 'application/json; charset=utf-8',
            "dataType": 'json',
            "cache": false,
            "data": {"obj": JSON.stringify(obj)},
            beforeSend: function(xhr) {
                // here it is
                xhr.setRequestHeader(header, token);
            }
            }).done(function(data){

                alert(JSON.stringify(data));
            });                 

The Java Spring MVC driver

@RequestMapping(value="agregarRenglonesFactura", method= RequestMethod.POST, consumes="application/json")
public String redAgregarRenglonesFactura(@RequestParam("obj") String objJson ) throws Exception{

     try{

         Gson gson = new Gson();

         ListadoDTO listado = gson.fromJson(objJson, ListadoDTO.class);

        Iterator<RenglonFacturaDTO> it = listado.getListadorenglon().iterator();

        System.out.println("*************************************** TAMAÑO LISTA ******************************************** : ");

        System.out.println("*************************************** TAMAÑO LISTA ******************************************** : " + listado.getListadorenglon().size());

        while(it.hasNext()){

            RenglonFacturaDTO renglonfacturadto = it.next();

        System.out.println("***************AGREGAR RENGLON*******************IDRENGLONREMITO: " + renglonfacturadto.getIdremito() + " CANTIDAD: " + renglonfacturadto.getCant());

        }

        return ("TAMAÑO LISTA:");
    } catch (Exception e){

            throw new Exception("ERROR :" + e.getMessage());
  }}   

And finally, the request returns a cod 200 ok, as if it had worked, but doing debug does not pass through the controller, nor does it return anything. And below it throws:

XML read error: element not found Location: link Line number 1, column 1:

    
asked by Marcos B. 30.09.2017 в 17:04
source

1 answer

1

It seems that you have a couple of errors, both in the generation of the request and in the controller.

In the request It is not necessary to encapsulate the object in another object, you can send the list directly:

"data": JSON.stringify(obj)

On the controller One of the wonders of Spring is to be able to parse the JSON directly to classes in your model, take advantage of it and change the parameter of the controller method to:

@RequestBody ListadoDTO listado
    
answered by 05.10.2017 в 14:28