假设我有以下Java类:
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Demo {
public int x;
public int y;
public List<Pair<Integer, Integer>> the_list;
}
我想从例如填充它以下json格式:
{ "x" : 1,
"y" : 2,
"the_list" : [[1,2],[3,4]]}
使用fastxml
ObjectMapper mapper = new ObjectMapper();
我可以在那里调用mapper.readTree(json)并填写我需要的一切。问题是我拥有的实际类(不是Demo)包含很多参数,我想从数据绑定功能中受益。
尝试平原:
mapper.readValue(json, Demo.class)
给出以下错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of
org.apache.commons.lang3.tuple.Pair, problem: abstract types either need to be mapped to
concrete types, have custom deserializer, or be instantiated with additional type
information
有没有办法将自定义解析与数据绑定混合?我查看了注释,但没有找到任何适合该目的的东西(我无法使用mixins来处理泛型,没有调用the_list的自定义setter可能是因为它是一个列表,JsonCreator不是一个选项,因为我没有写对类......)。
答案 0 :(得分:5)
您应该为Pair类编写自定义serializer/deserializer。
以下是一个例子:
public class JacksonPair {
static final String JSON = "{ \"x\" : 1, \n" +
" \"y\" : 2, \n" +
" \"the_list\" : [[1,2],[3,4]]}";
static class Demo {
public int x;
public int y;
public List<Pair<Integer, Integer>> the_list;
@Override
public String toString() {
return "Demo{" +
"x=" + x +
", y=" + y +
", the_list=" + the_list +
'}';
}
}
static class PairSerializer extends JsonSerializer<Pair> {
@Override
public void serialize(
Pair pair,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartArray(2);
jsonGenerator.writeObject(pair.getLeft());
jsonGenerator.writeObject(pair.getRight());
jsonGenerator.writeEndArray();
}
}
static class PairDeserializer extends JsonDeserializer<Pair> {
@Override
public Pair deserialize(
JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
final Object[] array = jsonParser.readValueAs(Object[].class);
return Pair.of(array[0], array[1]);
}
}
public static void main(String[] args) throws IOException {
final SimpleModule module = new SimpleModule();
module.addSerializer(Pair.class, new PairSerializer());
module.addDeserializer(Pair.class, new PairDeserializer());
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(module);
final Demo demo = objectMapper.readValue(JSON, Demo.class);
System.out.println("toString: " + demo);
System.out.println("Input: " + JSON);
System.out.println("Output: " + objectMapper.writeValueAsString(demo));
}
}
输出:
toString: Demo{x=1, y=2, the_list=[(1,2), (3,4)]}
Input: { "x" : 1,
"y" : 2,
"the_list" : [[1,2],[3,4]]}
Output: {"x":1,"y":2,"the_list":[[1,2],[3,4]]}