如何使用键值检索整个JSON对象?

时间:2019-04-03 16:04:18

标签: java android json gson json-deserialization

当然已经有人问过这个问题,但我无法为我的案子寻找解决方案。

我有两个Result文件:JSONquizzes.json。 第一个仅包含每个测验的标题和ID,第二个具有每个测验所需的所有数据。

quizzesQuestions.json

quizzes.json

[ { "_id": "1", "title": "blabla" }, { "_id": "2", "title": "blabla2" }, { "_id": "3", "title": "blabla3" }, { "_id": "4", "title": "blabla4" } ]

quizzesQuestions.json

我需要从[ { "quizId": "1", "questions": [ { "questionId": "1", "translations": [ { "lang": "fr", "label": "Quelle est la reponse ?", "answers": [ "reponse 1", "reponse 2", "reponse 3", "reponse 4" ], "trueAnswer": "reponse 1 2 3 or 4", "explanation": "parce que..." }, { "lang": "en", "label": "What is the answer ?", "answers": [ "answer 1", "answer 2", "answer 3", "answer 4" ], "trueAnswer": "answer 1 2 3 or 4", "explanation": "because..." }, { "lang": "de", "label": "What is the answer ?", "answers": [ "answer 1", "answer 2", "answer 3", "answer 4" ], "trueAnswer": "answer 1 2 3 or 4", "explanation": "because..." }, { "lang": "sp", "label": "What is the answer ?", "answers": [ "answer 1", "answer 2", "answer 3", "answer 4" ], "trueAnswer": "answer 1 2 3 or 4", "explanation": "because..." } ] }, { "questionId": "2", "translations": [ { "lang": "fr", "label": "Quelle est la reponse ?", "answers": [ "reponse 1", "reponse 2", "reponse 3", "reponse 4" ], "trueAnswer": "reponse 1 2 3 or 4", "explanation": "parce que..." }, { "lang": "en", "label": "What is the answer ?", "answers": [ "answer 1", "answer 2", "answer 3", "answer 4" ], "trueAnswer": "answer 1 2 3 or 4", "explanation": "because..." }, { "lang": "de", "label": "What is the answer ?", "answers": [ "answer 1", "answer 2", "answer 3", "answer 4" ], "trueAnswer": "answer 1 2 3 or 4", "explanation": "because..." }, { "lang": "sp", "label": "What is the answer ?", "answers": [ "answer 1", "answer 2", "answer 3", "answer 4" ], "trueAnswer": "answer 1 2 3 or 4", "explanation": "because..." } ] } ] } ] 文件中检索一个对象(目前,它将成为数据库),该对象等于特定的ID。这里只有一个ID为JSON的测验。

我已经可以使用1从第一个文件中检索所有测验,并将它们显示在列表中。现在,我只想检索具有与用户单击的ID相同的ID的测验,但我不知道如何进行。

这是我的Gson代码,如果它可以帮助您了解我想做什么:

Gson

1 个答案:

答案 0 :(得分:1)

您可以直接从JSON反序列化InputStream。另外,您无需使用org.json来读取JSON。尝试使用Gson直接解析数据:

private Map<String, Quizzes> loadQuizzes(InputStream jsonInputStream) throws IOException {
    Gson gson = new GsonBuilder().create();
    Type quizzesType = new TypeToken<List<Quizzes>>() {}.getType();

    try (InputStreamReader reader = new InputStreamReader(jsonInputStream, StandardCharsets.UTF_8)) {
        List<Quizzes> quizzes = gson.fromJson(reader, quizzesType);

        return quizzes
                .stream()
                .collect(Collectors.toMap(Quizzes::getQuizId, q -> q));
    }
}

现在,您可以按QuizzesMap中查找id对象。

另请参阅: