2

This is what my class looks like -

public class A {
    private Map<String, Object> objects = null;
    ....
}

My json would be like -

{
    "f1" : {
        "name" : "some name",
        "val" : 3
    },
    "f2" : {
        "arg": {
            some field/value pairs
        }
    }
}

What I want is to specify in the JSON itself the type to which it can be deserialized to. So the value for f1 would be converted to an object of class B and f2 would get converted to object of C.

My code will look like this -

Object o = objects.get("f1");
if (o instanceof B) {
  ...
} else if (o instanceof C) {
  ...
}

Is there a way to do this? I want the json to control the deserialization.

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
anindyaju99
  • 465
  • 1
  • 5
  • 16

1 Answers1

0

Yes, Jackson can use a type identifier if JSON document has it. This is usually done by using annotation @JsonTypeInfo.

There are multiple ways to add/use type identifier, both regarding how it is included in JSON document, and as to what kind of id is being used (type name or Java class name?).

The easiest way to see how things match is to actually start with a POJO, add @JsonTypeInfo annotation, and serialize it to see kind of JSON produced. And once you understood how inclusion works you can modify, if necessary, structure of JSON and/or Java class definition.

StaxMan
  • 113,358
  • 34
  • 211
  • 239