如何检索具有键值的整个 JSON 对象?

当然已经有人问过了,但我无法为我的情况搜索解决方案。


我有两个文件 :和 。第一个只有每个测验的标题和ID,第二个具有每个测验所需的所有数据。JSONquizzes.jsonquizzesQuestions.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..."

                    },

                


我需要从文件中检索一个对象(现在,它将成为将来的数据库),该文件等于特定的id。这里只有一个 id 为 的测验。JSON1


我已经能够从第一个文件中检索每个测验,并将它们显示在列表中。现在我希望能够仅检索与用户单击的测验具有相同ID的测验,但我不知道如何继续。Gson



UYOU
浏览 80回答 1
1回答

慕娘9325324

您可以直接从 反序列化。另外,您不需要使用 来读取 .尝试使用 直接解析数据:JSONInputStreamorg.jsonJSONGsonprivate Map<String, Quizzes> loadQuizzes(InputStream jsonInputStream) throws IOException {&nbsp; &nbsp; Gson gson = new GsonBuilder().create();&nbsp; &nbsp; Type quizzesType = new TypeToken<List<Quizzes>>() {}.getType();&nbsp; &nbsp; try (InputStreamReader reader = new InputStreamReader(jsonInputStream, StandardCharsets.UTF_8)) {&nbsp; &nbsp; &nbsp; &nbsp; List<Quizzes> quizzes = gson.fromJson(reader, quizzesType);&nbsp; &nbsp; &nbsp; &nbsp; return quizzes&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Quizzes::getQuizId, q -> q));&nbsp; &nbsp; }}现在,您可以从 中查找对象。QuizzesMapid
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java