Search code examples
javajsonenumsjsonschemajsonschema2pojo

Converting enum of variable length values using jsonschema2pojo


I am trying to create a json schema for a corresponding Java enum of variable length values. Information follows :

JSON tried :

"Info": {
      "type": "string",
      "enum": [
        "TITLE",
        "ADDRESS",
        "NAME";
      ]
     }

But this wouldn't provide the desired output instead the converted java class I am getting is

Current Output :

public static enum Info {
        TITLE("TITLE"),
        ADDRESS("ADDRESS"),
        NAME("NAME");
}

Required Java Output :

public enum Info {
    TITLE(45),
    ADDRESS(100),
    NAME(45);

    private Integer maxLength;

    Info(Integer maxLength) {
        this.maxLength = maxLength;
    }

    public Integer getMaxLength() {
        return maxLength;
    }
}

Unable to figure out a way to solve this. Would appreciate any help.


Solution

  • As far as I can tell this is currently not possible. If you look at the source code, then enums are generated by org.jsonschema2pojo.rules.enumRule. jsonschema2pojo provides a constructor to each enum which for your use case would need to take a single argument of type Integer. The constructor is generated in line 199 by the following code

    JVar valueParam = constructor.param(String.class, VALUE_FIELD_NAME);
    

    That is, the constructor is hard coded to always take a single argument of type String.

    The best you can probably do is to use the javaEnumNames property which allows you to specify the names and values of your enums (with the restriction that the value is always a string).

     {
      "javaEnumNames" : [
         "TITLE",
         "ADDRESS",
         "NAME"
      ],
      "enum" : [ 45, 100, 45 ]        
     }
    

    This JSON snippet produces

    ...
    TITLE("45"),
    ADDRESS("100"),
    NAME("45");
    ...