我目前正在尝试反序列化json响应。我的对象使用了构建器模式和使用者界面。
我正在对外部源执行http请求,并以json形式获得我的响应。所有响应都是字符串,看起来像:
{
"a": "198",
"b": "F",
"c": "30",
"d": "2019-02-01",
"e": "2019-12-31"
}
我将模型的名称和密钥更改为Model and Key,所以可能会有错别字,对此感到抱歉。
@JsonDeserialize(builder = Model.Builder.class)
public class Model {
private final Data data;
private Model() {
this.data = new Data();
}
/**
* @return key
*/
public Key getKey() {
return data.key;
}
/**
* @return Tax Form
*/
public String getTaxForm() {
return data.taxForm;
}
/**
* @return tax table
*/
public int getTaxTable() {
return data.taxTable;
}
/**
* @return tax percent
*/
public BigDecimal getTaxPercent() {
return data.taxPercent;
}
/**
* @return Valid from
*/
public LocalDate getValidFrom() {
return data.validFrom;
}
/**
* @return Valid to
*/
public LocalDate getValidTo() {
return data.validTo;
}
/**
* @param key key
* @return builder
*/
public static Builder getBuilder(Key key) {
return new Builder(key);
}
/**
* @param model the response
* @return builder
*/
public static Builder getBuilder(Model model) {
return new Builder(model);
}
/**
* builder
*/
public static class Builder {
@JsonDeserialize(as = Model.Data.class)
private final Data data;
@JsonCreator
private Builder(Key key) {
this.data = new Data();
this.data.key = key;
}
private Builder(Model model) {
this(model.data.key);
data.taxForm = model.data.taxForm;
data.taxTable = model.data.taxTable;
data.taxPercent = model.data.taxPercent;
data.validFrom = model.data.validFrom;
data.validTo = model.data.validTo;
}
public Builder with(Consumer<Data> consumer) {
consumer.accept(this.data);
return this;
}
public Model build() {
Model internalModel = new Model();
internalModel.data.key = data.key;
internalModel.data.taxForm = data.taxForm;
internalModel.data.taxTable = data.taxTable;
internalModel.data.taxPercent = data.taxPercent;
internalModel.data.validFrom = data.validFrom;
internalModel.data.validTo = data.validTo;
return internalModel;
}
}
/**
* Data
*/
public static final class Data implements Serializable {
private Key key;
@JsonProperty("b")
public String taxForm;
public int taxTable;
public BigDecimal taxPercent;
public LocalDate validFrom;
public LocalDate validTo;
}
}
public class Key {
private final String personalNumber;
public Key(@JsonProperty("a") String personalNumber) {
this.personalNumber = personalNumber;
}
public String getPersonalNumber() {
return personalNumber;
}
}
目前,我可以对a进行反序列化,但是所有其他字段都被遗漏了。我尝试在Data类中使用@JsonProperty,但这不起作用。有什么想法吗?