我有这个课:

@JsonIgnoreProperties(ignoreUnknown = true)
public class VehicleRestModel implements RestModel<Article> {

    @JsonProperty("idVehicle")
    public String id;

    public String name;
}

我从REST API中获得了以下JSON:
[
  { "idVehicle" : "1234DHR", "tm" : "Hyundai", "model" : "Oskarsuko"},
  //more vehicles
]

我希望模型的字段name是JSON的字段tmmodel串联在一起。我虽然必须使用JsonDeserializer,但是如何获取整个JSON对象呢?
class MyDeserializer implements JsonDeserializer<String, String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        // I need the entire JSON here, in order to concatenate two fields
    }
}

谢谢!

最佳答案

如果我理解您的问题,则可以有2个设置程序在同一私有字段上工作,然后可以使用@JsonProperty而不是该字段标记设置程序。
这可以帮助您:@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; }

}

如果需要,请谨慎使用null,因为null会作为文字附加在此演示代码中。

09-10 07:02
查看更多