您应该在自定义反序列化器类中隐藏这种丑陋的转换。它可能看起来像这样:
class PojoJsonDeserializer extends JsonDeserializer<Pojo> {
@Override
public Pojo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
InnerPojo innerPojo = jp.readValueAs(InnerPojo.class);
return innerPojo.toPojo();
}
private static class InnerPojo {
public List<String> key;
public String value;
Pojo toPojo() {
Pojo pojo = new Pojo();
pojo.setKey(new ArrayList<String>(key));
pojo.setValue(valueNTimes(value, key.size()));
return pojo;
}
private List<String> valueNTimes(String value, int nTimes) {
List<String> result = new ArrayList<String>(nTimes);
for (int index = 0; index < nTimes; index++) {
result.add(value);
}
return result;
}
}
}
您的 POJO 类现在看起来“自然”了:
@JsonDeserialize(using = PojoJsonDeserializer.class)
class Pojo {
private List<String> key;
private List<String> value;
public List<String> getKey() {
return key;
}
public void setKey(List<String> key) {
this.key = key;
}
public List<String> getValue() {
return value;
}
public void setValue(List<String> value) {
this.value = value;
}
@Override
public String toString() {
return "Pojo [key=" + key + ", value=" + value + "]";
}
}
简单的测试程序:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
public class JacksonProgram {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(json, Pojo.class));
}
}
印刷:
Pojo [key=[key1, key2, key3], value=[v1, v1, v1]]