我正在 IntelliJ 中使用调试器,在返回结果之前,数组完全正常,如您所见 here
但由于某种原因,浏览器中的响应看起来像 this
我不明白为什么这些字段是不可见的。
这就是我的 2 个模型的样子:
市:
@Entity
public class Municipality {
@Id
@JsonIgnore
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
}
预测
@Entity
public class Prediction {
@Id
@JsonIgnore
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
LocalDateTime tsPredictionMade;
LocalDateTime tsPredictionFor;
float pm10;
float pm25;
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
Municipality municipality;
}
这是我的 Controller :
@RestController
@RequestMapping("/predict")
public class PredictionController {
private MunicipalityService municipalityService;
private PredictionService predictionService;
@Autowired
public PredictionController(MunicipalityService municipalityService, PredictionService predictionService) {
this.municipalityService = municipalityService;
this.predictionService = predictionService;
}
@GetMapping
public List<Municipality> getPredictions(){
List<Municipality> result = municipalityService.getPredictions();
return result;
}
@GetMapping("/{municipality}")
public List<Prediction> getPredictionsForMunicipality(@PathVariable("municipality") String name){
List<Prediction> result = predictionService.getPredictions(name);
return result;
}
}
应用程序的其余部分(服务和持久层)非常标准。
这是什么原因呢?
最佳答案
您将需要模型的 getter 和 setter。 Jackson 库在将模型转换为 JSON 时需要它来访问其字段,这与将 resultSet 转换为模型时的 JPA 不同。这是代码:
预测
@Entity
public class Municipality {
@Id
@JsonIgnore
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDateTime getTsPredictionMade() {
return tsPredictionMade;
}
public void setTsPredictionMade(LocalDateTime tsPredictionMade) {
this.tsPredictionMade = tsPredictionMade;
}
public LocalDateTime getTsPredictionFor() {
return tsPredictionFor;
}
public void setTsPredictionFor(LocalDateTime tsPredictionFor) {
this.tsPredictionFor = tsPredictionFor;
}
public float getPm10() {
return pm10;
}
public void setPm10(float pm10) {
this.pm10 = pm10;
}
public float getPm25() {
return pm25;
}
public void setPm25(float pm25) {
this.pm25 = pm25;
}
public Municipality getMunicipality() {
return municipality;
}
public void setMunicipality(Municipality municipality) {
this.municipality = municipality;
}
}
直辖市
@Entity
public class Municipality {
@Id
@JsonIgnore
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
关于spring - 为什么 Controller 返回的 json 字段为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54268046/