我需要计算对象中从JSON获得的一些数据。那是我的JSON对象:
{
"myObject": {
"controlPoints": [10,15,20,25]
}
}
那是我的类,它映射到此JSON:
public class MyObject {
public List<Float> controlPoints;
public Float width;
public MyObject() {
width = controlPoints.get(0) / controlPoints.get(2); // in this point my controlPoints is empty.
}
}
如何在构造阶段使用从JSON获取的
controlPoints
计算宽度? 最佳答案
您可以使用@JsonCreator
将您的构造函数设为Jackson的Deserializer
:
@JsonCreator
public MyObject(List<Float> controlPoints, Float width) {
this.controlPoints = controlPoints;
this.width = this.controlPoints.get(0) / this.controlPoints.get(2);
}
要么
您可以创建一个
PostConstruct
方法,以在构造函数之后立即调用它@PostConstruct
public void calculateWidth(){
this.width = this.controlPoints.get(0) / this.controlPoints.get(2);
}