使用JsonReader读取JSON数组

时间:2017-03-21 10:48:48

标签: android

我使用JsonWrite和JsonReader开发了一个android应用程序。这是我的Json数组

[StudentListModel{rowId='1', userId='User1', userName='Vijil'}, StudentListModel{rowId='2', userId='User2', userName='Dhas'}] 

这是我的代码

private ArrayList<StudentListModel> readUser(JsonReader reader) throws IOException {
        String rowId = null;
        String userId = null;
        String userName = null;
        StudentListModel model = null;
        ArrayList<StudentListModel> userList = new ArrayList<>();
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("rowId")) {
                rowId = reader.nextString();
            } else if (name.equals("userId")) {
                userId = reader.nextString();
            } else if (name.equals("userName")) {
                userName = reader.nextString();
            } else {
                reader.skipValue();
            }
            model = new StudentListModel(rowId, userId, userName);
        }
        userList.add(model);
        reader.endObject();
        return userList;
    }

上面的代码只返回第二个列表(下面的列表)。

StudentListModel{rowId='2', userId='User2', userName='Dhas'}

我在循环部分出错,请帮我解决。

现在我修复了以下代码:

boolean isRowAdded = false, isIdAdded = false, isNameAdded = false;
while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("rowId")) {
                rowId = reader.nextString();
                isRowAdded = true;
            } else if (name.equals("userId")) {
                userId = reader.nextString();
                isIdAdded = true;
            } else if (name.equals("userName")) {
                userName = reader.nextString();
                isNameAdded = true;
            } else {
                reader.skipValue();
            }
            model = new StudentListModel(rowId, userId, userName);

            if (isRowAdded && isIdAdded && isNameAdded) {
                userList.add(model);
                /**
                 * reset insitial status for next iteration
                 */
                isRowAdded = false;
                isIdAdded = false;
                isNameAdded = false;
            }
        }

现在工作正确,但我不知道以后我会遇到任何问题?

2 个答案:

答案 0 :(得分:0)

解析完所有数组后,将模型添加到用户列表中。因此,您只添加您解析的最后一个值。只需将userList.add(model)调用移动到循环。

答案 1 :(得分:0)

while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("rowId")) {
            rowId = reader.nextString();
        } else if (name.equals("userId")) {
            userId = reader.nextString();
        } else if (name.equals("userName")) {
            userName = reader.nextString();
        } else {
            reader.skipValue();
        }
        model = new StudentListModel(rowId, userId, userName);

 userList.add(model);

    }

粘贴此代码