我真的很喜欢 playframework 中的 Form,但是当我有一个类的字段是Map<>
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonSetter;
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
public class GameState {
private String roomId = "";
private String woohoo = "";
@JsonDeserialize(as = LinkedHashMap.class, contentAs = Integer.class, keyAs = String.class)
private Map<String, Integer> players = new HashMap<String, Integer>();
@JsonProperty("players")
public Map<String, Integer> getPlayers() {
return players;
}
@JsonSetter("players")
public GameState setPlayers(Map<String, Integer> players) {
this.players = players;
return this;
}
public String getRoomId() {
return roomId;
}
public GameState setRoomId(String roomId) {
this.roomId = roomId;
return this;
}
public String getWoohoo() {
return woohoo;
}
public GameState setWoohoo(String woohoo) {
this.woohoo = woohoo;
return this;
}
}
在我的控制器中,我有以下静态形式:
static Form<GameState> gameForm = new Form<GameState>(GameState.class);
然后我有以下动作:
@BodyParser.Of(BodyParser.Json.class)
public static Result testAction() {
Form<GameState> form = gameForm.bindFromRequest();
if (!form.hasErrors()) {
GameState s = form.get();
if (!s.getPlayers().isEmpty()) {
return ok();
} else {
return badRequest("Need players!");
}
} else {
return badRequest("Wrong format!");
}
}
这会反序列化任何其他字段(当我有此类字段的类时包括在内)但List<>
不是字段。奇怪的是它适用于:Set<>
Map<>
GameState s = Json.fromJson(request().body().asJson(), GameState.class);
这是我用来测试动作的 curl 调用
curl -X POST http://localhost:9000/game/end/1 --data '{"roomId": "someid", "woohoo": "something", "players" : { "oliver" : "0" } }' -H 'Content-Type: application/json'
我正在使用播放 2.1。我是否有 @BodyParser.Of() 似乎也无关紧要。
问题:有没有办法使form.get()
工作正常?