我有一个defaultJson.json:
{
"crewType": "Cockpit",
"status": "CREATED",
"usePoints": true,
"points": [
{
"rank": "CPT",
"defaultPoints": 0,
"carryForwardPointsAllowed": false,
"carryForwardPointsMax": null,
"negativePointsAllowed": false,
"negativePointsLimit": null,
"accrualExpirationValue": null,
"accrualExpirationUnit": null
}
]
}
我为此json创建了一个模型,以便能够从中创建对象:
package com.xxxx.models
import lombok.AllArgsConstructor
import lombok.Builder
import lombok.Data
import lombok.NoArgsConstructor
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
class SomeConfig {
private Long version
private CrewType crewType
private ConfigStatus status
private String modifiedBy
private String modifiedTimestamp
private List<String> leaveTypes
private boolean usePoints
private List<PointsConfig> points
}
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
class PointsConfig {
private String rank
private int defaultPoints
private boolean carryForwardPointsAllowed
private Integer carryForwardPointsMax
private boolean negativePointsAllowed
private Integer negativePointsLimit
private Integer accuralValue
private AccrualUnit accuralUnit
}
enum ConfigStatus {
DRAFT,
CREATED
}
enum AccrualUnit {
DAY,
MONTH
}
enum CrewType {
CABIN("Cabin"),
COCKPIT("Cockpit"),
final String value
CrewType(String value) {
this.value = value
}
}
因此,我想创建“ SomeConfig”模型的对象,并能够修改该对象内的对象。问题在于它不起作用。
当我尝试以这种方式创建该对象时:
SomeConfig someConfig = new SomeConfig(DataSource.getTestData(defaultJson.json)
我收到此错误消息:
java.lang.IllegalArgumentException: No enum constant
com.xxxx.models.CrewType.Cockpit
at java.lang.Enum.valueOf(Enum.java:238)
at com.xxxx....
如果我违反了命名约定并且将枚举设为这样,它将起作用:
enum CrewType {
Cabin,
Cockpit
}
但是我们使用带有大写字母的枚举,这是一个很好的命名约定。
我如何解决这个问题,以便能够从此defaultJson以字符串形式接收crewType,并且如果此字符串为“ Cockpit”,则以某种方式将其转换为CrewType.COCKPIT;如果此字符串为“ Cabin”,则将其转换为CrewType.CABIN? >
答案 0 :(得分:1)
我猜该对象是使用其(由Lomok生成的)setter构造的。因此,如果您添加另一个带字符串的setter并将其映射到枚举,那可能会起作用。
public void setCrewType(final String crewTypeValue) {
CrewType crewType = CrewType.values().find { it.value == crewTypeValue }
If (!crewType) throw new IllegalArgumentException("Invalid crew type ${crewTypeValue}")
this.crewType = crewType
}