I'm implementing Java SpringBoot to make RestAPI application. I stuck with the loop below. The problem seems with the sub1_arr.add(subResult1);
I have run few test:
Print the SubResult1 for each iteration: The println show correct element but when add to sub1_arr it's become duplicate.
Test 1 (as shows in code) : This is suppose the initial code I wrote. Output is incorrect with duplicate output
Test 2 (as show in code) : having correct output but in string form.
while(rs.next())
{
if(rs.getString("status").equals("FAILED")) {
obj.put("result", "failed");
obj.put("msg", rs.getString("msg"));
}
else {
//mainResult - ignore for a while
mainResult.put("layer1_id", rs.getString("layer1_id"));
mainResult.put("layer1_name", rs.getString("layer1_name"));
//subResult - layer2
subResult1.put("layer2_id", rs.getString("layer2_id"));
subResult1.put("layer2_name", rs.getString("layer2_name"));
//test 1 - having incorrect output with all the element become duplicate
sub1_arr.add(subResult1);
//test 2 - having correct output but the output become string with \"xxx\"
sub1_arr.add(subResult1.toString());
}
}
//adding sub array to main result
mainResult.set("layer2", sub1_arr);
Get output (unexpected)
{"layer2":[
{"layer2_id" : "3", "layer2_name" : "name_3"},
{"layer2_id" : "3", "layer2_name" : "name_3"},
{"layer2_id" : "3", "layer2_name" : "name_3"}
]}
Expected output
{"layer2":[
{"layer2_id" : "1", "layer2_name" : "name_1"},
{"layer2_id" : "2", "layer2_name" : "name_2"},
{"layer2_id" : "3", "layer2_name" : "name_3"}
]}