Gson返回null

时间:2019-12-08 20:25:17

标签: java gson

我在使用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"}

1 个答案:

答案 0 :(得分:0)

您应阅读How To Ask,并确保下次代码为Minimal Complete Verifiable Example。这里不需要整个网络访问,您只需在字符串中传递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 = "me@example.org";
// ...