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)
StudentsDetails.java:
@Entity(name = "com.StudentDetails")
public class StudentDetails extends AbstractPersistable<Long> {
private long studentId;
private String name;
private long points;
private String courseName;
private long courseId;
public StudentDetails(long studentId, String name, long points, String courseName, long courseId) {
this.studentId = studentId;
this.name = name;
this.points = points;
this.courseName = courseName;
this.courseId = courseId;
}
public long getStudentId() {
return studentId;
}
public String getName() {
return name;
}
public long getPoints() {
return points;
}
public String getCourseName() {
return courseName;
}
public long getCourseId() {
return courseId;
}
}
I want to generate a JSON string like :
{
"items": [
{
"id": "123",
"students": [
{
"name": 'Matt',
"points": 3000,
"course_name": 'Science',
"course_id": 10
}
]
},
{
"id": "324",
"students": [
{
"name": 'Charley',
"points": 12348,
"course_name": Science,
"course_id": 20
}
]
},
{
"id": "898",
"error": {
"error_code": "500",
"error_message": "Details not found"
}
}
]
}
Part of Implementation code currently looks like :
for (int i = 0; i < studentDetails.size(); i++) {
Details details = new Details();
details.setName(studentDetails.get(i).getName());
details.setPoints(studentDetails.get(i).getPoints());
details.setCourseName(studentDetails.get(i).getCourseName());
details.setCourseId(studentDetails.get(i).getCourseId());
Listdetails.add(details);
item.setListDetails(Listdetails);
}
response = mapper.writeValueAsString(item);
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}]}]}
instead of
{"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}]}
Please help me to write a good implementation code to generate the correct JSON. (Note : It is not the real code - just a sample of the real code)
In short : I want to read the entries from the database table and make it as:
items array -> [
0th index : student_id, other related details (1107,['Matt',3000,'Science',10]
1st index : student_id, other related details(1108,['Charley',12348,'Science',20]
]