Send Json from jQuery to Spring mvc

0

I want to send a Json with this format

{
    "tarjetas": [
        {"nombre":nombre, "id": id, "lista": lista, "idLista": idLista},
        {"nombre":nombre, "id": id, "lista": lista, "idLista": idLista}
       ...
    ]
}

I build it like this:

var tarjetas  = [];
var objeto = {};

tarjetas.push({ 
        "nombre"    : arrayCards[i],
        "id"  : arrayCardsId[i],
        "nombreLista"    : nombreLista,
        "idLista": arrayCardsList[i]

    });
objeto.tarjetas = tarjetas;

For this I have this code in Javascript with jQuery:

 $.ajax({
      type: "POST",
      contentType : 'application/json; charset=utf-8',
      dataType : 'json',
      url: "http://localhost:8080/HelloSpringMVC/alo",
      data: JSON.stringify(objeto), 
      success :function(result) {
       // do what ever you want with data
     }

Controller code:

 @RequestMapping(value= "/j", method = RequestMethod.POST)

       public  String  recibe(@RequestBody Tarjetas tarjeta){

           System.out.println("Post");
           System.out.println(tarjeta.toString());
           return "index";
       }

Class Cards:

public class Tarjetas {
    private String tName;
    private String tId;
    private String nameList;
    private String idList;  
}

My problem is that I do not understand how to receive the Json in the controller, to work later with the data received, thanks.

    
asked by Silvia 29.03.2018 в 12:20
source

1 answer

1

Your json of input must have a direct mapping to the class you receive with @RequestBody

Given:

{
    "tarjetas": [ ... ]
}

You must define a class with a tarjetas attribute that is a listing (by the array in json ):

public class TarjetasWrapper {
    private List tarjetas;
}

Each item in the tarjetas listing has a json object:

{"nombre":nombre, "id": id, "lista": lista, "idLista": idLista}

So in java the List tarjetas must be from a class that has the attributes: nombre , id , lista , idLista :

public class Tarjetas {
    private List<Tarjeta> tarjetas;
}

public class Tarjeta {
    private String nombre;
    private String id;
    private String lista;
    private String idLista;
}
    
answered by 29.03.2018 / 17:07
source