我的建议是将文本文件的内容转换为 Json 文档,将 Json 文档直接映射到对象会更容易和更清晰。例如:
{
[
{
"question1":["answer1","answer2","answer3"]
},
{
"question2":["answer1","answer2","answer3"]
}
]
}
好的,让我们一步一步开始实现。
使用以下方法将 Gson 添加到您的项目中:
implementation 'com.google.code.gson:gson:2.8.5'
这里是 json 将被映射到的示例对象:
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Question {
@SerializedName("questionModel")
@Expose
private List<QuestionModel> questionModel = null;
public List<QuestionModel> getQuestionModel() {
return questionModel;
}
public void setQuestionModel(List<QuestionModel> questionModel) {
this.questionModel = questionModel;
}
}
将其保存在另一个名为 QuestionModel.java 的文件中
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class QuestionModel {
@SerializedName("question")
@Expose
private String question;
@SerializedName("answers")
@Expose
private List<String> answers = null;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public List<String> getAnswers() {
return answers;
}
public void setAnswers(List<String> answers) {
this.answers = answers;
}
}
这也是您的问题的示例 Json
{
"questionModel":[
{
"question" : "This is a sample question",
"answers" : ["answer1","answer2","answer3"]
}
]
}
您可以将 json 保存在 assets 文件夹中名为“sample.json”的文件中,读取内容并使用以下代码解析为对象:
String jsonSring = null;
try {
InputStream is = getAssets().open("data/sample.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonString = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
Gson gson = new Gson();
Question questionObject = gson.fromJson(jsonSring, Question.class);
所以你有了它,包含所有问题的 json 文件已映射到问题对象,该对象具有所有 QuestionModel 列表的定义。
如您所见,每个 QuestionModel 都有一个问题和可能的答案列表。