Pass object array via javascript to the controller

Asked

Viewed 2,436 times

1

How can I pass a javascript object array 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

The way I’m going, next to the Controller I get a string with all the objects together. How can I have access to each of the objects in the array on the Controller side?

  • What language do you have on the server side?

  • Which languages of the controller?

  • I’m sorry I didn’t mention it. It’s Java !

  • controller is JAVA or JSP ?

  • vc could save the javascript data in cookies so in the controller you can redeem cookies.

2 answers

1

How can I have access to each of the objects in the array on the Controller side?

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

  1. a variable of the array type named array
  2. for each row found in a table, an object in the array in format {codigo: a, quantidade: b, preco: c: desconto: d}
  3. before sending to the server, array is transformed into a string through the method JSON.stringify

Step 3 will transform your object array into one 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}
];

That’s a string representing the JSON generated by your logic, and that’s exactly what’s coming to your controller.

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

  1. you can change the way you send the data to the server, so that the data already arrives in the format that your controller waiting (independent of framework used)
  2. we can treat that string and rebuild the elements on the back-end side.

There are several frameworks that will help you work with JSON in the JAVA. I recommend using one of the frameworks next: gson and the jackson.

Solving the problem with the GSON framework

Create a class that will represent your javascript objects in the back-end:

public class ItemTabela {

    public Long codigo;

    public Long desconto;

    public String preco;

    public Long quantidade;

}

As the string that we are receiving represents a array, we will declare a type to indicate to the framework the kind of feedback we expect:

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

Now just use the method .fromJson(reader, type) 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);

1

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

In PHP it will be json_decode() in Nodejs is JSON.parse(). In Java I think you need to use an external library. Take a look here (http://json.org/ - JSON documentation), at the bottom of the page, for libraries that do this: http://json.org/

In a so Soen’s answer 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"));
    }
}

Still exists another question with good links (including what I have gathered upon).

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();
  • And what is this part of JS for? Or how can I use it on the java side?

  • @Hugomachado the JS part is a suggestion to optimize the code you have, optional.

  • àh Ok ;) I have difficulty sending the object array to the java controller

Browser other questions tagged

You are not signed in. Login or sign up in order to post.