[英]How to convert JSON file to List
我正在嘗試打開JSON
,其中每個 object 4 個屬性都有一個對象數組:問題、答案 1、答案 2、答案 3、正確答案。 我創建了一個名為 Question 的Class
。 我想創建一個array
/問題list
,然后使用它
JSON 位於名為questions.json
的資產文件夾中
public class Question{
private String title;
private String a1, a2, a3;
private String cA;
public Question(String title, String a1, String a2, String a3, String cA){
this.title = title;
this.a1 = a1;
this.a2 = a2;
this.a3 = a3;
this.cA = cA;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getA1() {
return a1;
}
public void setA1(String a1) {
this.a1 = a1;
}
public String getA2() {
return a2;
}
public void setA2(String a2) {
this.a2 = a2;
}
public String getA3() {
return a3;
}
public void setA3(String a3) {
this.a3 = a3;
}
public String getcA() {
return cA;
}
public void setcA(String cA) {
this.cA = cA;
}
}
你有兩個步驟
從文件中獲取 JSON 字符串,使用從資產中讀取文件
從 JSON 字符串中提取項目使用如何將 JSON 數組轉換為 Java 列表。 我正在使用斯文森
你可以試試這個:
String json = Files.readString(Paths.get("path\of\your\json\file"));
Map<String,List<Example>> result1 = parser.parse(Map.class, json);
List<Question> list = new ArrayList<Value>(result1.values());
1)讀取您的 json 文件並將其放入字符串變量中
2)在 map 中反序列化您的 json
3)將您的 map 轉換為問題列表
您可以創建一個新的 Class Questions.java ,其中包含一個問題列表 object 並使用以下內容轉換為列表。
public class Questions {
List<Question> questions;
//getter setter }
Questions questions = null;
try {
JsonReader reader = new JsonReader(new FileReader(
"replace with path"));
questions = new Gson().fromJson(reader, Questions.class);
} catch (Exception e) {
e.printStackTrace();
}
示例 json:
{
"questions": [
{
"title": "What is 1+2 ?",
"a1": "1",
"a2": "2",
"a3": "3",
"cA": "3"
},
{
"title": "What is 2*3 ?",
"a1": "6",
"a2": "4",
"a3": "3",
"cA": "6"
}
]}
您可以使用以下方法從文件中讀取並將 JSON 數組轉換為問題列表。
public String readJsonFromFile(String filePath) throws IOException, ParseException {
String json = Files.readString(Paths.get("file path"));
return new JSONParser().parse(json).toString();
}
public List<Question> convert(String JsonString) throws JsonMappingException, JsonProcessingException {
ObjectMapper om = new ObjectMapper();
CollectionType typeReference =
TypeFactory.defaultInstance().constructCollectionType(List.class, Question.class);
List<Question> questions = om.readValue(JsonString, typeReference);
return questions;
}
如果您的 JSON 密鑰和 Java class 字段不同,請使用 @JsonPropery 注釋到 Z1D7AEZB8DC8ED5122449015 字段
import com.fasterxml.jackson.annotation.JsonProperty;
public class Question {
@JsonProperty("question")
private String title;
@JsonProperty("answer 1")
private String a1;
@JsonProperty("answer 2")
private String a2;
@JsonProperty("answer 3")
private String a3;
@JsonProperty("correct answer")
private String cA;
//setters & getters
}
所需的 Jars:
傑克遜注釋.jar
傑克遜核心.jar
傑克遜-databind.jar
json-simple.jar //用於解析Json文件為String
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.