joelittlejohn / jsonschema2pojo

Generate Java types from JSON or JSON Schema and annotate those types for data-binding with Jackson, Gson, etc
http://www.jsonschema2pojo.org
Apache License 2.0
6.24k stars 1.66k forks source link

Is it possible to ignore unknown enum values in schema json? #1480

Closed alinagb closed 1 year ago

alinagb commented 1 year ago

After a basic enum schema is generated, the enum class has

    @JsonCreator
    public static MyEnum fromValue(String value) {
        MyEnum constant = CONSTANTS.get(value);
        if (constant == null) {
            throw new IllegalArgumentException(value);
        } else {
            return constant;
        }
    }

And in my case it is possible to pass an unkown value, but the code will throw IllegalArgumentException. I'd like it just to be ignored or having a default value.

Is there any possibility to just ignore unknown values or set a default value in the json schema?

 "properties": {
   "myEnum": {
      "type": "array",
       "items": {
            "type": "string",
             "enum": ["one", "two", "three"]
         }
    }
}
joelittlejohn commented 1 year ago

I think you want this Jackson feature:

DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL

alinagb commented 1 year ago

Thanks it's working having the DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL. I was thinking maybe there is a solution having a kind of property directly in the json for ignoring the unknown value

joelittlejohn commented 1 year ago

No, I don't think there's any way to express this in a schema. By definition, and enum means 'only these values and no other'.

unkish commented 1 year ago

It should be possible to "customize" EnumRule behavior by extending/overriding methods in latter and providing instance of it through extended RuleFactory: https://github.com/joelittlejohn/jsonschema2pojo/blob/25bfc76091ed8f1deaac91a6d1f479ec4a3db6ee/jsonschema2pojo-maven-plugin/src/main/java/org/jsonschema2pojo/maven/Jsonschema2PojoMojo.java#L300-L308