[英]Json InvalidFormatException : Cannot deserialize value of type HandType from String "flush"
我在將 Json 反序列化為 Java object 時遇到一些問題。 我的 Json 看起來像這樣:
"players": [
{
"id": "12345678",
"handtype": "flush"
},
{
"id": "12345679",
"handtype": "straight"
}
]
我的 Java 類如下所示:
public class Players {
@JsonProperty(value = "id")
private String id;
@JsonProperty(value = "handtype")
private HandType handType;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setHandType(HandType handType) {
this.handType = handType;
}
public HandType getHandType() {
return handType;
}
public enum HandType {
HIGH_CARD("high_card"),
PAIR("pair"),
TWO_PAIRS("two_pairs"),
THREE_OF_A_KIND("three_of_a_kind"),
STRAIGHT("straight"),
FLUSH("flush"),
FULL_HOUSE("full_house"),
FOUR_OF_A_KIND("four_of_a_kind"),
STRAIGHTFLUSH("straightflush"),
ROYALFLUSH("royalflush");
private String handName;
HandType(String handName) {
this.handName = handName;
}
public String getHandName() {
return handName;
}
}
似乎有問題的是它需要“FLUSH”,但我給了他“flush” - 盡管我在枚舉中有應該匹配小寫場景的字符串。 我應該如何編寫代碼以消除異常?
首先,您的players
是List<Player>
,而不是Players
:
@JsonProperty(value = "players")
List<Player> players;
所以每個Player
看起來像這樣(注意我將屬性設置為final
,我認為一旦 object 被初始化,你實際上並不希望它們是可變的):
public class Player {
@JsonProperty(value = "id")
private final String id;
@JsonProperty(value = "handtype")
private final HandType handType;
@JsonCreator
public Player(@JsonProperty(value = "id") String id, @JsonProperty(value = "handtype") HandType handType) {
this.id = id;
this.handType = handType;
}
}
最后,您的枚舉中的 getter 應由@JsonValue
注釋,以便告訴 Jackson 從何處獲取枚舉的字符串值(否則,默認情況下,Jackson 將嘗試通過其.toString()
反序列化枚舉表示在您的情況下是FLUSH
,而不是flush
):
@JsonValue
public String getHandName() {
return handName;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.