简体   繁体   English

使用Gson将Json转换为Java Object

[英]Using Gson to convert Json into Java Object

I am currently working on a project where I am using the Steam Web API. 我目前正在开发一个使用Steam Web API的项目。 The API returns data in JSON format and I wanted to make a Java program that uses this data. API以JSON格式返回数据,我想制作一个使用这些数据的Java程序。 Here is the following JSON format from the API: 以下是API中的以下JSON格式:

{
    "response": {
        "players": [
            {
                "steamid": "---",
                "communityvisibilitystate": 1,
                "profilestate": 1,
                "personaname": "---",
                "lastlogoff": 1429915502,
                "profileurl": "---",
                "avatar": "---",
                "avatarmedium": "---",
                "avatarfull": "---",
                "personastate": 0
            }
        ]

    }
}

I am using Google's JSON API called Gson and I am having trouble setting up the Java classes so that I can use the fromJson() method. 我正在使用谷歌的JSON API,名为Gson,我在设置Java类时遇到问题,因此我可以使用fromJson()方法。

From the JSON data, I know that there is an array of players objects that contain all the data. 从JSON数据中,我知道有一系列包含所有数据的players对象。 The one thing that is confusing me is the outer tag called response . 令我困惑的一件事是外部标签叫做response I know that I have to construct a class representing the players objects but do I also have to create a class that represents response since it encloses players ? 我知道我必须构建一个代表players对象的类,但是我还必须创建一个代表response的类,因为它包含了players吗?

As of right now, I have a file named Response.java that contains the following: 截至目前,我有一个名为Response.java的文件,其中包含以下内容:

public class Response {

    private ArrayList<Player> playerSummaries = new ArrayList<Player>();

    public String toString() {
        return playerSummaries.get(0).toString();
    }

}


class Player {
    private String steamid;
    private String personaname;


    public String getSteamID() {
        return steamid;
    }

    public void setSteamID(String newSteamID) {
        steamid = newSteamID;
    }

    public String getPersonaName() {
        return personaname;
    }

    public void setPersonaName(String name) {
        personaname = name;
    }

    //Rest of getters and setters omitted.

    @Override
    public String toString() {
        return "<<" + "steamid=" + steamid + "\n" + "name=" + personaname + "\n" + ">>";
    }
}

I only included the variables that I plan to use. 我只包括了我打算使用的变量。 The JSON data above is contained in a String called jsonData and this is what I am testing in my main method: 上面的JSON数据包含在一个名为jsonData的String中,这就是我在main方法中测试的内容:

Response response = gson.fromJson(jsonData, Response.class);

System.out.println(response.getPlayerAt(0));

However, running this gives me an IndexOutOfBoundsException. 但是,运行它会给我一个IndexOutOfBoundsException。 It seems as if Gson was unable to get the information and store it into an object? 好像Gson无法获取信息并将其存储到对象中? Could anyone shed some light on this problem I am having? 谁能解释一下我遇到的这个问题? I am mostly curious to know if I have set up my classes correctly. 我很想知道我是否正确设置了我的课程。

Replace 更换

private ArrayList<Player> playerSummaries = new ArrayList<Player>();

with

private ArrayList<Player> players = new ArrayList<Player>();

GSON uses reflection to look up which field it should populate. GSON使用反射来查找它应该填充的字段。 In your case it is looking up whether you have a field named players which you do not. 在你的情况下,它正在查找你是否有一个你没有的名为players的领域。

You also do not need to instantiate the field, GSON will do that for you. 您也不需要实例化该字段,GSON会为您执行此操作。

EDIT: 编辑:

You also need a wrapper class around your top-level object. 您还需要一个围绕顶级对象的包装类。 So 所以

class MyObject {
    public Response response;
}

MyObject myObject = gson.fromJson(jsonData, MyObject.class);

Why you are using 你为什么用

System.out.println(response.getPlayerAt(0));

You should use 你应该用

response.getPlayerSummaries.get(0); 

where getPlayers is the getter of your 其中getPlayers是你的getter

   private ArrayList<Player> playerSummaries = new ArrayList<Player>();

getPlayerSummaries will get the arraylist and then you will use get method of arraylist class over it. getPlayerSummaries将获得arraylist,然后你将使用arraylist类的get方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM