Disable message from JSON to POJO with Jackson
How would you deserialize a JSON document for a POJO using Jackson if you don't know exactly which type of POJO to use without validating the message. Is there a way to register a set of POJOs with Jackson so that he can pick one based on the message?
The script I am trying to solve receives JSON messages over a pipe and deserializes into one of several POJOs based on the content of the message.
source to share
I am not aware of the mechanism 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 need to validate the fields in the JsonNode to resolve the type.
source to share
If you have some flexibility in your JSON library take a look at Jackson . It has a BeanDeserializer that can be used for this purpose.
source to share
BeanDeserializer, in Jackson, is deprecated. However, I had the same problem and solved it using Google GSon . Take a look at this example.
Given your POJO datatype:
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 cannot serialize objects with circular references, as this will lead to infinite recursion.
-
Deserialization
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
source to share