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);