我有這門課:
@JsonIgnoreProperties(ignoreUnknown = true)
public class VehicleRestModel implements RestModel {
@JsonProperty("idVehicle")
public String id;
public String name;
}
我從REST API擷取此JSON:
[
{ "idVehicle" : "1234DHR", "tm" : "Hyundai", "model" : "Oskarsuko"},
//more vehicles
]
我希望我的模型的字段名稱是JSON的字段tm和模型連接配接.我雖然使用了JsonDeserializer但是,我怎樣才能獲得整個JSON對象?
class MyDeserializer implements JsonDeserializer {
@Override
public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// I need the entire JSON here, in order to concatenate two fields
}
}
謝謝!
最佳答案 如果我了解你的問題,你可以讓2個setter在同一個私有字段上工作,然後你可以用@JsonProperty而不是字段來标記setter.
這可以幫到你: @JsonProperty annotation on field as well as getter/setter
您也可以使用@JsonGetter(“var”)和@JsonSetter(“var”)而不是@JsonProperty.
編輯:好的,一個解決方案.這是我送出的最醜陋的代碼,但如果你想要一個快速的東西,你不能真正修改POJO原始界面(字段,getter)
public class VehicleRestModel {
private String concatValue = "";
private int splitIndex;
@JsonSetter("var1")
public setVar1(String var1){ concatValue = var1 + concatValue.substring(splitIndex,concatValue.length()); ; splitIndex = var1.length(); }
@JsonSetter("var2")
public setVar2(String var2){ concatValue = concatValue.substring(0,splitIndex) + var2; }
}
如果您在意,請注意空值,因為它們會在此示範代碼中作為文字附加.