InputStream到JsonObject - GSON

时间:2015-05-06 19:19:36

标签: java android gson

我将这个api的结果转换为JsonObject时遇到了很多麻烦。

"结果"无论我尝试做什么,都会保持无效。

  URL url = new URL(urlString);
  InputStream input = url.openStream();
  Reader reader = new InputStreamReader(in, "UTF-8");
  JsonResult result  = new Gson().fromJson(reader, JsonResult.class);

JsonResult类

public class JsonResult {
    private String status;
    private Meta meta;
    private ArrayList<Player> players;
}

class Meta{
    private String count;
}

JSON:

{"status":"ok","meta":{"count":12},"data":[{"nickname":"DataBase","account_id":500566109},{"nickname":"database007","account_id":514382449},{"nickname":"Database04","account_id":504367425},{"nickname":"database08","account_id":515081772},{"nickname":"database1","account_id":503282284},{"nickname":"database1221","account_id":506709044},{"nickname":"database123","account_id":508409172},{"nickname":"database1337","account_id":501661259},{"nickname":"database169","account_id":503884400},{"nickname":"database2","account_id":504337382},{"nickname":"database93","account_id":518691821},{"nickname":"databaseking66","account_id":505911069}]}

注意:这是针对学校项目的

注2:我确实从SO中检查并测试了很多其他解决方案,但没有找到或理解正确的解决方案。

编辑1:

public class JsonResult {
    @SerializedName("status")
    public String status;
    @SerializedName("meta")
    public Meta meta;
    @SerializedName("data")
    public Player[] players;
}

class Meta{
    @SerializedName("count")
    private String count;
}

玩家类

public class Player {

    private int account_id;
    private String nickname;

    public Player(int account_id, String nickname){
        this.account_id = account_id;
        this.nickname = nickname;
    }


    //Generated
    public void setAccount_id(int account_id) {
        this.account_id = account_id;
    }

    //Generated
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String toString() {
        return this.account_id + this.nickname;
    }
}

1 个答案:

答案 0 :(得分:4)

在你的JsonResult类中更改

public class JsonResult {
    private String status;
    private Meta meta;
    @SerializedName("data")
    private ArrayList<Player> players;
}