Gson返回空值

wbrvyc0a  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(159)

我在JSON方面遇到了麻烦,我目前有这个类将JSON响应从我的API转换为对象,但它返回的所有值都为null -

public class User {

    public String username;

    public User(String username) throws IOException {
        this.username = username;
        URL url = new URL(urlhere);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 1.0.3705)");
        String response = ApiRequest.getResponse(connection);
        connection.disconnect();
        Gson gson = new Gson();
        gson.fromJson(response, this.getClass());
    }

    public int id;
    public String email;
    public String role;
    public String plan;
    public String planEndDate;

}

字符串
我对json很陌生,请记住这一点,我可能错过了一些东西。
JSON响应示例:

{"id":7,"username":"xx","email":"xx","role":"administrator","plan":"xx","planEndDate":"xx"}

uqcuzwp8

uqcuzwp81#

这里不需要整个网络访问,你可以只在String中传递JSON。一个做网络I/O的构造函数也是一个非常糟糕的主意,因为它很慢,而且在单元测试中很痛苦。
也就是说,gson.fromJson返回一个User对象,但您永远不会对它做任何事情;它只是超出了作用域。
我会把代码改成这样:

public class User {
    public String username;
    public int id;
    public String email;
    public String role;
    public String plan;
    public String planEndDate;

    public static User findByName(String username) throws IOException {
         String json = downloadUserData(username);
         return new Gson().fromJson(json, User.class);
    }

    public static String downloadUserData(String username) throws IOException {
        URL url = new URL(urlhere);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 1.0.3705)");
        String response = ApiRequest.getResponse(connection);
        connection.disconnect();
        return response;
    }
}

字符串
这样,您仍然可以手动构建用户,或者在必要时从某处下载他们的数据。

User downloaded = User.findByName("me");

User json = new Gson().fromJson("{\"id\": 1, \"username\": \"me\", ... \"}", User.class);

User manually = new User();
manually.username = "me";
manually.email = "[email protected]";
// ...

相关问题