java - 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)添加到问题列表中
解决方案
您可以使用 gson 库,其中 YourClass 包含与 json 文件完全相同的属性(是的,您可以使用问题列表或您需要的任何集合作为属性),然后使用相同的逻辑:
import com.google.gson.GsonBuilder
var gson = new GsonBuilder().create();
return gson.fromJson(yoursJsonString, YourClass);
推荐阅读
- php - 如果对象 id 已知,Laravel 获取对象属性
- android - 我无法在活动中导入 java.util.date
- tensorflow - model.compile 的两种描述得到不同的结果
- clang - 我可以使用哪些 clang 函数来查找具有 '&' 的声明,例如 'int *m = &b'?
- python - 将 float 的 tuple-1 列表转换为 int 集
- azure - 如何安装 Azure Az - 无法将值“2.0.0-preview”转换为类型“System.Version”
- mysql - 计算列和总和
- netezza - 如何从 Netezza 删除用户
- java - 元素 web-app 必须在 Intellij 中声明错误
- asp.net-mvc - 将文件夹添加到 ASP.net MVC 5 站点中的所有 URL