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.
- a variable of the array type named
array
- for each row found in a table, an object in the
array
in format {codigo: a, quantidade: b, preco: c: desconto: d}
- 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:
- 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)
- 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);
What language do you have on the server side?
– Sergio
Which languages of the controller?
– user21494
I’m sorry I didn’t mention it. It’s Java !
– Hugo Machado
controller is JAVA or JSP ?
– Daniel Omine
vc could save the javascript data in cookies so in the controller you can redeem cookies.
– Daniel Omine