Pass array of objects via javascript to the controller

1

How can I pass an array of javascript objects to the controller?

JQUERY

var array = [];
var $linhas = $("#vendaTabela tbody > tr");
$linhas.each(function () {
   var x = {
    id: $(".codigo",this).text(),
    quantidade: $(".quantidade",this).text(),
    preco: $(".preco",this).text(),
    desconto: $(".desconto",this).text()
           }
    array.push(x);
        })

myJSRoutes.---.ajax({
            success: function () {
                $.smallBox({
                    title: "Documento adicionado com sucesso.",
                    content: "<i class='fa fa-clock-o'></i> <i></i>",
                    color: "#C46A69",
                    iconSmall: "fa fa-check fa-2x fadeInRight animated",
                    timeout: 4000
                });
            },
            data: {
                exemplo: JSON.stringify(array)
            }
        });

CONTROLLER

LANGUAGE: Java

In the way I'm doing, on the Controller side I get a string with the objects all together. How can I on the Controller side access each of the objects in the array?

    
asked by anonymous 06.03.2015 / 16:18

2 answers

1

You are passing a serialized JSON to the controler so you need to parse that string.

In PHP it will json_decode() in NodeJs is JSON.parse() . In Java I think you have to use an external library. Take a look here ( link - JSON documentation) at the bottom of the page for libraries that do this: link

In a reply to SOen suggest this function:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

There's also another question with good links (including what I've put together).

However an optional suggestion for your JS, using .map() :

var array = $("#vendaTabela tbody > tr").map(function () {
    return {
        id: $(".codigo", this).text(),
        quantidade: $(".quantidade", this).text(),
        preco: $(".preco", this).text(),
        desconto: $(".desconto", this).text()
    }
}).get();
    
06.03.2015 / 16:24
1
  

How can I access the Controller side of each array object?

To answer your question, let's take a closer look at the situation presented.

  • An array variable named array
  • For each row found in a table, an object is added in array in format {codigo: a, quantidade: b, preco: c: desconto: d}
  • Before sending to the server, array is transformed into a string using the JSON.stringify
  • Step 3 will turn your array of objects into a string similar to:

    [
        {'codigo':1,'quantidade':19,'preco':'$8.54','desconto':21},
        {'codigo':2,'quantidade':31,'preco':'$8.46','desconto':2},
        {'codigo':3,'quantidade':14,'preco':'$8.96','desconto':5},
        {'codigo':4,'quantidade':5,'preco':'$5.37','desconto':18},
        {'codigo':5,'quantidade':7,'preco':'$8.87','desconto':2}
    ];
    

    This is a string that represents the JSON generated by your logic, and that is exactly what is coming in your controller.

    Based on this information, we can answer your question in 2 ways:

  • You can change the way you send the data to the server, so that the data already arrives in the format your controller expects (regardless of the framework used)
  • We can treat this string and rebuild the elements on the backend side.
  • There are several frameworks that will help you work with JSON in JAVA . I recommend using one of the following frameworks : gson and jackson .

    Solving the problem with the GSON framework

    Create a class that will represent your javascript objects on the backend:

    public class ItemTabela {
    
        public Long codigo;
    
        public Long desconto;
    
        public String preco;
    
        public Long quantidade;
    
    }
    

    As the string we're receiving represents an array , we'll declare an type to indicate for the framework the type of return that we expect:

    Type type = new TypeToken<ArrayList<ItemTabela>>() {}.getType();
    

    Now just use the .fromJson(reader, type) of class com.google.gson.Gson :

    String json = "[{'codigo':1,'quantidade':19,'preco':'$8.54','desconto':21},{'codigo':2,'quantidade':31,'preco':'$8.46','desconto':2},{'codigo':3,'quantidade':14,'preco':'$8.96','desconto':5},{'codigo':4,'quantidade':5,'preco':'$5.37','desconto':18},{'codigo':5,'quantidade':7,'preco':'$8.87','desconto':2}]";
    
    Gson gson = new Gson();
    
    List<ItemTabela> itens = gson.fromJson(json, type);
    
        
    13.10.2015 / 06:44