我真的很喜欢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 -X POST http://localhost:9000/game/end/1 --data '{"roomId": "someid", "woohoo": "something", "players" : { "oliver" : "0" } }' -H 'Content-Type: application/json'
我正在使用Play 2.1。如果我在这个动作上有@ BodyParser.Of(),那似乎也没关系。
问题:有没有办法让form.get()
正常工作?