InputStream to JsonObject - GSON

2022-09-01 07:53:59

我在将结果从此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

在您的 JsonResult 类更改中

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

答案 2

推荐