问题
How would you deserialize a JSON document to a POJO using Jackson if you didn't know exactly what type of POJO to use without inspecting the message. Is there a way to register a set of POJOs with Jackson so it can select one based on the message?
The scenario I'm trying to solve is receiving JSON messages over the wire and deserializing to one of several POJOs based on the content of the message.
回答1:
I'm not aware of a mechanism that you are describing. I think you will have to inspect the json yourself:
Map<String, Class<?>> myTypes = ...
String json = ...
JsonNode node = mapper.readTree(json);
String type = node.get("type").getTextValue();
Object myobject = mapper.readValue(json, myTypes.get(type));
If you don't have a type field you will have to inspect the fields in the JsonNode in order to resolve the type.
回答2:
If you have flexibility in your JSON library, take a look at Jackson. It has a BeanDeserializer that can be used for this very purpose.
回答3:
BeanDeserializer, in Jackson is deprecated. However, I had the same problem and I solved it using Google's GSon. Have a look at this example.
Given your POJO data type:
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
Serialization
BagOfPrimitives obj = new BagOfPrimitives(); Gson gson = new Gson(); String json = gson.toJson(obj); // ==> json is {"value1":1,"value2":"abc"}
Note that you can not serialize objects with circular references since that will result in infinite recursion.
Deserialization
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
来源:https://stackoverflow.com/questions/9813461/deserialize-message-from-json-to-pojo-using-jackson