Java枚举接受的值

huangapple go评论63阅读模式
英文:

Java Enum Accepted Values

问题

一个枚举数据类型被定义为类的属性。

public class Foo {

  public enum Direction {

    NORTH("north"),
    EAST("east"),
    SOUTH("south");

    public final String label;

    private Direction(String label) {
      this.label = label;
    }

  }

  private Direction direction;
  ...
}

当我解析 JSON 数据以匹配这个类时,我遇到了一个错误

字符串 "east":不是枚举类接受的值之一:[NORTH、EAST、SOUTH、WEST]

通过将枚举数据全部更改为小写,可以解决这个问题。如果我想使用 Java 枚举数据类型的约定,需要什么来解决这个问题?

英文:

An enum data type is defined as an attribute of a class.

public class Foo {

  public enum Direction {

    NORTH("north"),
    EAST("east"),
    SOUTH("south");

    public final String label;

    private Direction(String label) {
      this.label = label;
    }

  }

  private Directory direction;
  ...
}

When I parse a Json data to match the class, I get an error

String "east": not one of the values accepted for Enum class: [NORTH, EAST, SOUTH, WEST]

This problem can be resolved by changing the enum data to all low case. If I want to use the Java enum data type convention, what is needed to resolve the problem?

答案1

得分: 4

如果您正在使用Jackson来反序列化Foo类,您可以:

public class Foo {

  public enum Direction {

    NORTH("north"),
    EAST("east"),
    SOUTH("south");

    @JsonValue
    public final String label;

    private Direction(String label) {
      this.label = label;
    }

  }

  private Direction direction;
  // 必须存在direction的getter和setter方法
}

// 然后通过以下方式进行反序列化:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"direction\":\"north\"}";
Foo f = mapper.readValue(json, Foo.class);

这将导致一个带有Direction.NORTH字段的Foo对象。
有关在使用Jackson时的其他可能性,请查看 https://www.baeldung.com/jackson-serialize-enums

英文:

If you are using Jackson to deserialise the Foo class, you could:

public class Foo {

  public enum Direction {

    NORTH("north"),
    EAST("east"),
    SOUTH("south");

    @JsonValue
    public final String label;

    private Direction(String label) {
      this.label = label;
    }

  }

  private Direction direction;
  // getter, setter for direction must exist
}

// then deserialise by:
ObjectMapper mapper = new ObjectMapper();
String json = "{\"direction\":\"north\"}";
Foo f = mapper.readValue(json, Foo.class);

This will result in a Foo object with a Direction.NORTH field.
For other possibilities when using Jackson check https://www.baeldung.com/jackson-serialize-enums

huangapple
  • 本文由 发表于 2020年10月24日 03:04:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64505920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定