问题描述
我尝试处理请求
{
"city": "city","date": "2020-08-26T12:15:54.428Z","time": {
"sum":"123"
}
}
我的目标是处理此请求。诀窍是,我尝试使用带有可选参数的Builder模式(根据有效Java。Joshua Bloch)。据我了解,我不必发送所有时间值。只需要总和。 我尝试通过邮递员将RequestBody中的Sport对象发送给我的控制器。
因此,我为Sport创建了POJO类:
@Entity
@Table(name = "sport")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Sport {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "date")
private Date date;
@Column(name = "city")
private City city;
@Type(type = "time")
private Time time;
}
和 时间生成器:
package pl.project.model;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
@JsonDeserialize(builder = Time.Builder.class)
public class Time {
private final String bike;
private final String run;
private final String sum;
private Time(Builder builder) {
bike = builder.bike;
run = builder.run;
sum = builder.sum;
}
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
String bike = "-";
String run = "-";
final String sum;
Builder(String sum) {
this.sum = sum;
}
Builder bike(String bike) {
this.bike = bike;
return this;
}
Builder run(String run) {
this.run = run;
return this;
}
Time build() {
return new Time(this);
}
}
}
仍然出现错误:
JSON parse error: Cannot construct instance of `pl.project.model.Time$Builder` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `pl.project.model.Time$Builder` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (pushbackinputstream); line: 14,column: 7] (through reference chain: pl.project.model.Sport[\"time\"])"
我尝试了许多stackoverflow解决方案,但对我没有任何作用。
有人可以帮助我吗?
解决方法
Builder
类必须具有以该属性命名的方法,和/或使用@JsonProperty
来命名值。
使用@JsonProperty
作为构造函数参数
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
String bike = "-";
String run = "-";
final String sum;
Builder(@JsonProperty("sum") String sum) { // must explicitly name the property
this.sum = sum;
}
Builder bike(String bike) {
this.bike = bike;
return this;
}
Builder run(String run) {
this.run = run;
return this;
}
Time build() {
return new Time(this);
}
}
使用构建器的“ setter”方法
@JsonPOJOBuilder(withPrefix = "")
public static class Builder {
String bike = "-";
String run = "-";
String sum;
Builder sum(String sum) { // standard builder "setter" method
this.sum = sum;
return this;
}
@JsonProperty("bike") // must explicitly name for non-standard method name
Builder setBicycle(String bike) {
this.bike = bike;
return this;
}
Builder run(String run) {
this.run = run;
return this;
}
Time build() {
if (this.sum == null) // need to validate here,since property is otherwise optional
throw new IllegalStateException("Required property missing: sum");
return new Time(this);
}
}