-1

I have a JSON Array which has for example following objects in it:

A Car and the Color of the car which is saved like

0:{Car: "Toyota", Color: "Blue"}
1:{Car: "Porsche", Color: "Black"}
2:{Car: "Ferrari", Color: "Red"}

I need to loop through that array in java and for every run, and make a Java Object out of the JSON objects (Cars in this case) in the array, something like

Test current = new Test(Car, Color)

and after that I want it to save in the java array like

data.add(current)

I already started to do a loop but I can't get further:

private List<Test> data;

private void setObjects() {
    String newData = request.getParameter("data");

    try {
        JSONArray jsonarr = new JSONArray(Data);

        System.out.println(jsonarr.toString());
    }   
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
J.Doe
  • 586
  • 2
  • 8
  • 30

2 Answers2

1

Try this:

JSONArray jsonarr = new JSONArray(Data);
for (int i = 0; i < jsonarr.length(); i++) {
    JSONObject jsonobject = jsonarr.getJSONObject(i);
    Test current = new Test(jsonobject.getString("Car"), jsonobject.getString("Color"));
    data.add(current);
}
M.Boukhlouf
  • 303
  • 2
  • 10
0

As a suggestion, I would create a class "Car":

public class Car() {
    private String brand;
    private String color;

    ... //add setters and getters here
}

and then use an ObjectMapper for the parsing of the input, resulting in an OOP approach.