将JSON与记录中的列表绑定

时间:2018-12-21 16:56:35

标签: java json spring-boot

当我必须使用一个简单的json时,我就这样做

 HttpEntity<String> entity = new HttpEntity<>("parameters", header);
            ResponseEntity<List<RelatorioResponse>> response = rt.exchange(targetUrl, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RelatorioResponse>>() {
            });
            List<RelatorioResponse> responses = response.getBody();

我的回复课

 @JsonProperty("relatorioID")
    private Integer relatorioID;

    @JsonProperty("professorID")
    private Integer professorID;

    @JsonProperty("alunoID")
    private Integer alunoID;

//getter setter

一切都按预期完成,我可以正常处理数据。

问题是要从JSON接收数据,并在每个记录中嵌入一个列表, 像这样:

[
  {
    "classID": 10,
    "id of students who missed class": [
      1,
      2
    ]
  },
  {
    "classID": 20,
    "id of students who missed class": [
      3,
      4,
      8 
    ]
  }
]

完整的json

 [{"classID":10,"id of students who missed class":[1,2]},{"classID":20,"id of students who missed class":[3,4]},
{"classID":50,"id of students who missed class":[2,33,9,45,35]},{"classID":56,"id of students who missed class":[1,6,7]},{"classID":20,"id of students who missed class":[12]},
{"classID"87,"id of students who missed class":[3,6,8,45,7,9]},{"classID":12,"id of students who missed class":[1,2,74,45,36]},{"classID":20,"id of students who missed class":[2,9,36,5]},
{"classID":41,"id of students who missed class:"[5,6,9,8,7]}]

在这种情况下,这应该是我的绑定类,一个Class类型的对象以及在其中的整数数组,@ JsonProperty注释在哪里?

1 个答案:

答案 0 :(得分:0)

您可以使用int[]来映射学生的ID:

public class Attendance {

    @JsonProperty("classID")
    private int classId;

    @JsonProperty("id of students who missed class")
    private int[] missingStudentIds;

}

并读取完整的JSON作为数组:

ObjectMapper mapper = new ObjectMapper();
Attendance[] obj = mapper.readValue(json, Attendance[].class);