1

here is my enum:

public enum Etichetta {
FT/IR, //problem with '/' character
IB,
COMM;
}

how can i get that special character? Keep in mind that I use this object that is sent to me in the body via post and then I have to save to db.

public class PrimaNota {
    private Integer id;
    private String impo;
    private String codC;
    private Etichetta etichetta;
}

In post method they send me FT/IR as a Etichetta. How can I do?

2 Answers2

3

This problem is not caused by enums. You cannot use the special character "/" in any identifier, such as an enum, record, class, function or variable.

You can find the allowed characters in https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html. However even if something is legal, that does not necessarily mean that is a good idea, as there are certain naming conventions, such as UpperCamelCase for class names.

Identifier:
IdentifierChars but not a Keyword or BooleanLiteral or NullLiteral

IdentifierChars:
JavaLetter {JavaLetterOrDigit}

JavaLetter:
any Unicode character that is a "Java letter"

JavaLetterOrDigit:
any Unicode character that is a "Java letter-or-digit"

The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII dollar sign ($, or \u0024) and underscore (_, or \u005f). The dollar sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems. The underscore may be used in identifiers formed of two or more characters, but it cannot be used as a one-character identifier due to being a keyword.

The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).

However what you can do is create a constructor that takes a string argument and pass that to a field and call that constructor when creating the enums. In this manner you can associate all kinds of strings with your enum constants.

Konrad Höffner
  • 11,100
  • 16
  • 60
  • 118
0
 public enum Etichetta {
   FT_IR("FT/IR"),
   IB("IB"),
   COMM("COMM");

    private final String value;

    Etichetta(String value) {
        this.value = value;
    }

    @JsonValue
    public String getValue() {
        return value;
    }

    @JsonCreator
    public static Etichetta forValue(String value) {
        return Arrays.stream(Operation.values())
            .filter(op -> op.getValue().equals(value))
            .findFirst()
            .orElseThrow(); // depending on requirements: can be .orElse(null);
    }
}

or with Jackson 2.6.2

   public enum MyEnum {
       @JsonProperty("FT/IR")  FT_IR,
       @JsonProperty("IB")  IB,
       @JsonProperty("COMM")  COMM;
  }
Arun
  • 3,701
  • 5
  • 32
  • 43
  • I didn’t see any mention of JSON or Jackson in the question. – VGR Jun 16 '21 at 16:04
  • Those functions are public functions. The setter and getter can be overridden to use those functions then. – Arun Jun 16 '21 at 17:33