1

I'm trying to understand how to do JSON deserialization using Jackson. My JSON looks like this:


{
    "__type": "base",
    "__ConfigAType": "Sona",
    "sonaString": "some test string",
    "allRequiredSchemas": "[\"abc\"]",
    "stepName": "GL1",
    "preReq": []
}

My classes look like this:

public class Step {
    private String stepName;
    private List<Step> preReq;
    private ModuleConfig moduleConfig;
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "__type")
@JsonSubTypes({
        @JsonSubTypes.Type(value = BaseConfig.class, name = BaseConfig.TYPE)
})
public interface ModuleConfig {

}

public class BaseConfig implements ModuleConfig {
    public static final String TYPE = "base";
}

@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.PUBLIC_ONLY)
@JsonTypeName(SonaConfig.TYPE)
@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.PROPERTY,
        property = "__ConfigAType")
@JsonSubTypes({
        @JsonSubTypes.Type(value = SonaConfig.class, name = SonaConfig.TYPE)
})
public abstract class ConfigA extends BaseConfig {
    public static final String TYPE = "ConfigA";
    private List<String> allRequiredSchemas;

    abstract Boolean execute(String input);
    abstract String getConfigAType();
}

public class SonaConfig extends ConfigA {
    public static final String TYPE = "SONA";
    private String sonaString;
    @Override Boolean execute(String input) {
        return true;
    }

    @Override String getConfigAType() {
        return "Sona";
    }
}


When I try to deserialize the JSON into a Step Class I get the following error: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "__type"

I'm parsing it the following way: Step x = new ObjectMapper().readerFor(Step.class).readValue(json);

Because the field preReq will contain a list of objects of type Step, I would ideally like it to reference another JSON blob instead of creating one giant JSON. Hence I've a class of type BaseConfig and my plan is to have a RefConfig which can read references to other JSON files.

user1692342
  • 5,007
  • 11
  • 69
  • 128
  • You may want to look at `JsonTypeIdResolver` and `@JsonIdentityReference(alwaysAsId = true)` for your use case. Also, something is wrong if you have one inheritance hierarchy, but two fields for determining the final type. I don't have a good reference yet, but have a look at this question for parent-child-serialization: https://stackoverflow.com/questions/60265882/parent-child-relation-between-two-objects-causes-json-stackoverflowerror/60267029 – sfiss Mar 11 '20 at 15:56

0 Answers0