I have following result for the query select * from student where courseName = 'Science';
Results:
student_id | name | points | course_name | course_id |
+----------+--------+--------+---------------+-----------+
1107| Matt | 3000 | Science | 10 |
| 1108| Charley| 12348 | Science | 20 |
2 rows in set, 2 warnings (0.00 sec)
Part of Implementation code currently looks like :
List<StudentDetails> studentDetailss = StudentDetailsRepository
.findByCourseId(Request.getCourseId());
List<Student> student = new ArrayList<>();
List<Item> studentList = new ArrayList<>();
Response response = new Response();
for (StudentDetails student : studentDetailss) {
IndividualItem studentItem = new IndividualItem();
studentItem.setId(student.getId());
Offer offer = new Offer();
offer.setName(studentDetailss.getName());
offer.setTotalPoints(studentDetailss.getPoints());
offer.setCourseName(studentDetailss.getCourseName());
offer.setCourseId(studentDetailss.getCourseId());
Student.add(offer);
studentItem.setOfferList(Student);
studentList.add(studentItem);
Response.setItems(studentList);
}
json_text = mapper.writeValueAsString(Response);
Above code prints the wrong JSON like :
{"items":[{"id":"1107","details":[{"name":"Matt", "points":3000,"course_name":"Science","course_id":10},{"name": "Charley",points":12348,"course_name":"Science","course_id":20}]},{"id":"1108","details":[{"name":"Matt", "points":3000,"course_name":"Science","course_id":10},{"name": "Charley",points":12348,"course_name":"Science","course_id":20}]}]}
But I need to generate following JSON instead of the above one :
{"items":[{"id":"1107","details":[{"name":"Matt", "points":3000,"course_name":"Science","course_id":10}]},{"id":"1108","details":[{"name": "Charley",points":12348,"course_name":"Science","course_id":20}]}]}
(Note : It is not the real code - just a sample of the code)
The above problem was solved by initializing the array list 'student' inside the for loop:
The code changed like :
List<StudentDetails> studentDetailss = StudentDetailsRepository
.findByCourseId(Request.getCourseId());
List<Item> studentList = new ArrayList<>();
Response response = new Response();
for (StudentDetails student : studentDetailss) {
IndividualItem studentItem = new IndividualItem();
studentItem.setId(student.getId());
Offer offer = new Offer();
offer.setName(studentDetailss.getName());
offer.setTotalPoints(studentDetailss.getPoints());
offer.setCourseName(studentDetailss.getCourseName());
offer.setCourseId(studentDetailss.getCourseId());
Student.add(offer);
studentItem.setOfferList(Student);
studentList.add(studentItem);
Response.setItems(studentList);
}
json_text = mapper.writeValueAsString(Response);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.