2

I'm using jackson and I have a problem with the method returning the Object object. This means that different classes can be passed in .json file and I want to parse them to the corresponding object from my project.

    @XmlAnyElement (lax = true)
  public Object getEntity() {
    return this.entity;
  }

I always get LinkedHashMap in return since JSON isn't sure what object should it expect.

  1. Is it possible to annotate the method with the list of expected class names?

  2. Is it possible to annotate the method with the list of expected objects that should be returned?

Luka
  • 21
  • 3
  • Can you add how are you deserializing the json, and a fragment of it to see if it has the class type indicated? The only issue I got with deserializing Object was solved with: `PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder().allowIfBaseType(Object.class).build();` in one of the new Jackson versions – Franjavi Dec 02 '19 at 14:09
  • 2
    Take a look at [Inheritance with Jackson](https://www.baeldung.com/jackson-inheritance) and `@JsonTypeInfo` and `@JsonSubTypes` annotations. See: [Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY doesn't work as expected](https://stackoverflow.com/questions/18757431/jackson-jsontypeinfo-as-external-property-doesnt-work-as-expected), [Jackson polymorphic JSON deserialization of an object with an interface property?](https://stackoverflow.com/questions/21485923/java-jackson-polymorphic-json-deserialization-of-an-object-with-an-interface-pr). – Michał Ziober Dec 02 '19 at 15:19
  • @Franjavi `@XmlAnyElement (lax = true) @JsonProperty(value = "tag") @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, defaultImpl = Tag.class) public Object getEntity() { return this.entity; }` This way only the Tag.class is expected and it works for this specific class. Is it possible, for example, to put a list of expected classes? – Luka Dec 04 '19 at 08:28
  • Do you have control over the json produced? Could you add to the description a fragment of it? – Franjavi Dec 04 '19 at 13:41

0 Answers0