#java #json
Вопрос:
У меня возникли некоторые проблемы с десериализацией Json в объект Java. Мой 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;
}
}
Что кажется неправильным, так это то, что он ожидает «ФЛЕШ», но я даю ему «флеш» — хотя в перечислении у меня есть строки, которые должны соответствовать сценарию со строчными буквами.
Как я должен написать свой код, чтобы избавиться от исключений ?
Ответ №1:
Во-первых, ваш players
-это а List<Player>
, а не а Players
:
@JsonProperty(value = "players")
List<Player> players;
Таким образом , каждый Player
из них будет выглядеть следующим образом (обратите внимание, что я создал свойства final
, я не думаю, что вы на самом деле хотите, чтобы они изменялись после инициализации объекта).:
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;
}
}
И в заключение, получатель в вашем перечислении должен быть аннотирован, @JsonValue
чтобы указать Джексону, где получить строковое значение перечисления (иначе , по умолчанию, Джексон попытается десериализовать перечисление по его .toString()
представлению, что в вашем случае FLUSH
не flush
так).:
@JsonValue
public String getHandName() {
return handName;
}