Android Studio-将json列表添加到数组列表

时间:2018-10-11 14:39:11

标签: java android json firebase

我正在使用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 =新的QuestionOptions(op2,op1,op4,op3);             QuestionOptions obj =新的QuestionOptions(op2,op1,op4,op3);                             QuestionStructure问题=新的QuestionStructure(Question,answer,obj,book,章节,类型,QID);             QuestionStructure问题=新的QuestionStructure(问题,答案,obj,书,章,类型,QID);

QuestionsList.add(question);             QuestionsList.add(question);

    }

}

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

1 个答案:

答案 0 :(得分:0)

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

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