在javascript中访问Java Enum字段

时间:2017-05-05 13:52:19

标签: javascript java spring enums

我试图在java脚本中访问此枚举的facility字符串

public enum FacilityEnum {

    CAR_VALET("carValet"),
    INDOOR("indoorPark"),
    DISABLED_ACCESS("disabledAccess"),
    EV_CHARGE("evCharge"),

    private String facility;

    private FacilityEnum(String facility) {
        this.facility = facility;
    }

    public String getFacility() {
        return facility;
    }

    public void setFacility(String facility) {
        this.facility = facility;
    }



}

此枚举用于Facility.class

@Entity
public class Facility {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long facilityId;

    @Enumerated(EnumType.STRING)
    private FacilityEnum service;


    @ManyToMany(mappedBy = "facilities")
    @JsonBackReference("parks-facilities-services")
    private Set<Park> parks;
    }


    public FacilityEnum getService() {
        return service;
    }

    public void setService(FacilityEnum service) {
        this.service = service;
    }

与Park.class有一个ManyToMany关系。

当我需要在javascript

中使用facility字符串时,问题出现了

这是javascript感兴趣的部分,我使用的是Spring + Thymleaf

var parcheggi = JSON.parse([[${parks}]]); //my list of Parks
parcheggi.forEach(function (arrayItem) { //it's ok

            var parcheggio = arrayItem;
            var services = parcheggio.facilities; //it's ok, i get Facility objects
            var servicesDiv = '<div>';
            services.forEach(function (service){
                var s = service; //the single Facility

                servicesDiv += '<img src="/images/park_icons/facilities/' + s.service + '.png" />'
            });
            servicesDiv += '</div>';

 //rest of the code...

在这种情况下,s.service是粗略的枚举(CAR_VALET,INDOOR ...),如果我尝试s.service.facility我得到了未定义..我需要carValet,室内,disabledAccess等等。

2 个答案:

答案 0 :(得分:0)

执行所需操作的一种方法是使用toString方法配置对象映射器以序列化枚举。您可以将以下内容添加到对象映射器配置中:

 objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);

(请注意,以前的Jackson版本具有相同的属性,但它有所不同)。

然后只需将toString添加到你的枚举:

@Override
public String toString ()
{
    return facility;
}

答案 1 :(得分:0)

您收到undefined,因为您的枚举无法在JSON中反序列化,您有两种选择:

  • 要么更改Enum的实现,所以它只包含String个常量,它将由Jackson正确映射。

您的代码将是:

public enum FacilityEnum {
    CAR_VALET,
    INDOOR,
    DISABLED_ACCESS,
    EV_CHARGE;
}
  • 或者您应该覆盖Enum中的toString()方法,以便它可以 被反序列化并以String返回。

您的代码将是:

public enum FacilityEnum {

  CAR_VALET("carValet"),
    INDOOR("indoorPark"),
    DISABLED_ACCESS("disabledAccess"),
    EV_CHARGE("evCharge"),

    private String facility;

  private FacilityEnum(String facility) {
    this.facility = facility;
  }

  public String getFacility() {
    return facility;
  }

  public void setFacility(String facility) {
    this.facility = facility;
  }

  @Override
  public String toString() {
    return facility;
  }

}