首页 > 解决方案 > Android studio - 将 json 列表添加到数组列表中

问题描述

我正在使用 android studio 和 firebase 构建一个应用程序,它是一个测验应用程序,我正在从 firebase 回答问题:

        public void onDataChange(DataSnapshot dataSnapshot)
        {
public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren())
            {
    for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {


                type =(String)singleSnapshot.child("type").getValue();
        type = (String) singleSnapshot.child("type").getValue();
                answer= (String) singleSnapshot.child("answer").getValue();
        answer = (String) singleSnapshot.child("answer").getValue();
                book=(String)singleSnapshot.child("book").getValue();
        book = (String) singleSnapshot.child("book").getValue();
                chapter=(String) singleSnapshot.child("chapter").getValue();
        chapter = (String) singleSnapshot.child("chapter").getValue();
                op1=(String)singleSnapshot.child("op1").getValue();
        op1 = (String) singleSnapshot.child("op1").getValue();
                op2=(String)singleSnapshot.child("op2").getValue();
        op2 = (String) singleSnapshot.child("op2").getValue();
                op3=(String)singleSnapshot.child("op3").getValue();
        op3 = (String) singleSnapshot.child("op3").getValue();
                op4=(String)singleSnapshot.child("op4").getValue();
        op4 = (String) singleSnapshot.child("op4").getValue();
                Question=(String)singleSnapshot.child("question").getValue();
        Question = (String) singleSnapshot.child("question").getValue();
                QID=singleSnapshot.getKey();

        QID = singleSnapshot.getKey();

QuestionOptions obj =new QuestionOptions(op2,op1,op4,op3); QuestionOptions obj = new QuestionOptions(op2, op1, op4, op3); QuestionStructure question = new QuestionStructure(Question,answer,obj,book,chapter, type,QID); QuestionStructure question = new QuestionStructure(Question, answer, obj, book, chapter, type, QID);

QuestionsList.add(问题); QuestionsList.add(问题);

    }

}

如何更改代码,以便应用程序将问题从 json 文件(也来自 firebase)添加到问题列表中

标签: javaandroidjsonfirebase

解决方案


您可以使用 gson 库,其中 YourClass 包含与 json 文件完全相同的属性(是的,您可以使用问题列表或您需要的任何集合作为属性),然后使用相同的逻辑:

import com.google.gson.GsonBuilder
var gson = new GsonBuilder().create();
return gson.fromJson(yoursJsonString, YourClass);

推荐阅读