从Java对象生成正确的JSON - Jackson

时间:2017-08-22 12:00:08

标签: java json jackson iteration

我对查询select * from student where courseName = 'Science';

有以下结果

结果:

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)

部分实施代码目前如下:

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

上面的代码打印错误的JSON,如:

 {"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}]}]}

但是我需要生成以下JSON而不是上面的那个:

 {"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}]}]} 

(注意:这不是真正的代码 - 只是代码的一个示例)

1 个答案:

答案 0 :(得分:0)

通过在f​​or循环中初始化数组列表'student'来解决上述问题:

代码改为:

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