1

I would need to convert JSON to POJO, which implements following marker interface:

import com.fasterxml.jackson.annotation.JsonTypeInfo;

import java.io.Serializable;

@JsonTypeInfo(
        use = JsonTypeInfo.Id.CLASS,
        include = JsonTypeInfo.As.PROPERTY,
        property = "@class"
)
public interface MyInterface extends Serializable {
}

this is pojo:

public class MyPojo implements MyInterface
{
    private static final long serialVersionUID = 1L;

    private String phonetype;

    private String cat;

    //getters + setters
}

and this is snippet code where I have to use it, but I don't know what I have to do:

String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
ObjectMapper mapper = new ObjectMapper();
MyPojo myPojo = mapper.readValue(json, MyPojo.class);//here I get exception: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class path.to.MyPojo]: missing type id property '@class'
    //        at [Source: (String)"{"phonetype":"N95","cat":"WP"}"; line: 1, column: 30]

When I don't implement interface into MyPojo, everything works correctly without exception, but I would need implement it. I use library jackson-databind-2.9.8

I would like to asking you, if you have any suggestion how can I solve it or if does it exist another approach how parse Pojo implementing interface showed above. I mean something missing in my interface but I don't know what.

Thank you so much

Martin
  • 11
  • 2
  • If you're using JSON (which is usually a good choice), don't complicate matters with `Serializable`. – chrylis -cautiouslyoptimistic- Jul 06 '20 at 16:28
  • You need to specify `type` in `JSON` to recognise which implementation should be used for an interface. For example: [Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY...](https://stackoverflow.com/questions/18757431/jackson-jsontypeinfo-as-external-property-doesnt-work-as-expected), [Jackson polymorphic JSON deserialization of an object with an...](https://stackoverflow.com/questions/21485923/java-jackson-polymorphic-json-deserialization-of-an-object-with-an-interface-pr), [unmarshilling JSON data...](https://stackoverflow.com/questions/16800896/java-unmarshilling-json-data-containg-abstract-type) – Michał Ziober Jul 06 '20 at 19:29

1 Answers1

0

You may try to use a custom deserializer as shown in the following link How arbitrary JSON string can be deserialized to java POJO?

Prashanth D
  • 137
  • 1
  • 6
  • Thank you, I tried it, but I always get same exception = InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class path.to.MyPojo]: missing type id property '@class' – Martin Jul 06 '20 at 23:31