使用@JsonInclude(NON_DEFAULT)时GET上的DropWizard 400错误

时间:2015-10-11 23:55:09

标签: java json jackson dropwizard

当我使用Postman向400 unable to parse JSON发送GET时出现games/错误。

GameResource:

@Path("/games")
@Produces(MediaType.APPLICATION_JSON)
public class GameResource {
    @GET
    public List<Game> getGames() {
        ArrayList<Game> l = new ArrayList<Game>();
        l.add(new Game(100));
        return l;
    }
}

游戏:

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Game {
    protected int id; 
    protected int whoseTurn;
    protected int winner;
    protected char[][] board;

    public Game(int id, int turn, int winner, char[][] board) {
        this.id=id;
        this.whoseTurn=turn;
        this.winner=winner;
        this.board=board;
    }

    public int getId() {
        return id;
    }       

    public int getWhoseTurn() {
        return whoseTurn;
    }

    @JsonInclude(Include.NON_DEFAULT)
    public int getWinner() {
        return winner;
    }

    @JsonIgnore
    public char[][] getBoard() {
        return board;
    }

如果我删除getWinner上的注释,它可以正常工作。为什么会这样? DropWizard不支持Include.NON_DEFAULT吗?其他注释似乎工作正常......

1 个答案:

答案 0 :(得分:4)

除非你有一个no-arg构造函数,否则

Include.NON_DEFAULT将无法工作,例如,以下内容将起作用(没有setter它相当无用)。

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;

public class Game {
    protected int id;
    protected int whoseTurn;
    protected int winner = -1;
    protected char[][] board;

    public Game() { }

    public Game(int id, int turn, int winner, char[][] board) {
        this.id = id;
        this.whoseTurn = turn;
        this.winner = winner;
        this.board = board;
    }

    public int getId() {
        return id;
    }

    public int getWhoseTurn() {
        return whoseTurn;
    }

    @JsonInclude(Include.NON_DEFAULT)
    public int getWinner() {
        return winner;
    }

    @JsonIgnore
    public char[][] getBoard() {
        return board;
    }
}

这是有效的,因为有一个默认的无参数构造函数,且wins有一个默认值。 JavaDoc可能会为您提供更多帮助。