从JSON到没有表名的对象

时间:2018-06-09 10:16:50

标签: java android json gson

我试图将JSON非常简单地解析为对象(使用GSON)

我的JSON:

[{"username":"admin","password":"admin","name":"admin","email":"admin@admin.com"},{"username":"mark20","password":"mark123","name":"mark","email":"mark@steew.com"}]

是否有2个用户,因此我创建了2个用户,用户列表和用户:

public class Users {

    ArrayList<User> users;

    Users(ArrayList<User> users){
        this.users = users;
    }

}

public class User {

    String userame;
    String password;
    String name;
    String email;

}

这是我的解析代码:

public void onResponse(Call call, Response response) throws IOException {
            String body = response.body().string();
            Gson gson = new GsonBuilder().create();
            Users users = gson.fromJson(body, Users.class);
        }

当然在变量body中我有正确的JSON,但在最后一道我得到了:

JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

这里有什么不对?如何解决?

2 个答案:

答案 0 :(得分:2)

您的json是User的数组,而不是数组Users的包装User

像这样读你的json:

User[] users = gson.fromJson(body, User[].class);

如果您想要ArrayList<>

List<User> userList = Arrays.asList(users);

另一种方法是使用TypeToken

Type listType = new TypeToken<ArrayList<User>>(){}.getType();
List<User> userList = gson.fromJson(body, listType);

答案 1 :(得分:0)

如果我正在阅读我在其他地方正确阅读的内容,请尝试:

public void onResponse(Call call, Response response) throws IOException {
            String body = response.body().string();
            Gson gson = new GsonBuilder().create();
            User[] users = gson.fromJson(body, User[].class);
        }