后端经常会使用到枚举类,想让前端知晓这个枚举类中常量的含义,要将其返回给前端。
直接返回枚举类的话,前端只会显示枚举名称,不是很友好。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
@Getter
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum PhaseEnum {
//0:接地端,1:导线端A相, 2: 导线端B相,3: 导线端C相,4: 接地端A相,5: 接地端B相,6: 接地端C相
PHASE_0(0, "接地端"),
PHASE_1(1, "导线端A相"),
PHASE_2(2, "导线端B相"),
PHASE_3(3, "导线端C相"),
PHASE_4(4, "接地端A相"),
PHASE_5(5, "接地端B相"),
PHASE_6(6, "接地端C相");
private final Integer code;
private final String name;
PhaseEnum(Integer code, String name) {
this.code = code;
this.name = name;
}
/**
*根据name查code
**/
public static Integer getCodeByName(String name) {
for (PhaseEnum phaseEnum : PhaseEnum.values()) {
if (phaseEnum.getName().equals(name)) {
return phaseEnum.getCode();
}
}
return null;
}
/**
*根据name查枚举类
**/
public static PhaseEnum getPhaseEnum(String name) {
for (PhaseEnum temp : PhaseEnum.values()) {
if (temp.getName().equals(name)) {
return temp;
}
}
return null;
}
}
/**
* 获取地线部件的相位枚举
**/
@RequestMapping(value = "/getEarthwirePhase.do", method = {RequestMethod.GET})
@ResponseBody
@ApiOperation(value = "获取地线部件的相位枚举", notes = "获取地线部件的相位枚举")
public Object getEarthwirePhase() {
return RestResponse.success(PhaseEnum.values());
}