在flatter中将JSON解析为模型
我有一些存储在JSON中的数据,我正试图映射到它各自的模型类在flatter中将JSON解析为模型,json,flutter,dart,Json,Flutter,Dart,我有一些存储在JSON中的数据,我正试图映射到它各自的模型类 { "1":{ "answer":"This is question 1", "question":"This is answer 1" }, "2":{ "answer":"This is question 2", "question":"This is answer 2" }, "3":{ "answer":"This is question 3", "question":"This is answ
{
"1":{
"answer":"This is question 1",
"question":"This is answer 1"
},
"2":{
"answer":"This is question 2",
"question":"This is answer 2"
},
"3":{
"answer":"This is question 3",
"question":"This is answer 3"
},
"4":{
"answer":"This is question 4",
"question":"This is answer 4"
},
"5":{
"answer":"This is question 5",
"question":"This is answer 5"
}
}
我想将问题
和答案
字段映射到模型,但是,当它们嵌套在一个数字上时,如何实现这一点?通常我会创建父类别的另一个模型类,但是如果父类别没有标记,您会怎么做
class FaqModel {
String question;
String answer;
FaqModel({this.question, this.answer});
FaqModel.fromJson(Map<String, dynamic> json) {
question = json["question"];
answer = json["answer"];
}
}
类模型{
字符串问题;
字符串回答;
FAQ模型({this.question,this.answer});
FaqModel.fromJson(映射json){
question=json[“question”];
answer=json[“answer”];
}
}
只需获取密钥并进行迭代,如下所示:
final data = {
"1":{
"answer":"This is question 1",
"question":"This is answer 1"
},
"2":{
"answer":"This is question 2",
"question":"This is answer 2"
},
"3":{
"answer":"This is question 3",
"question":"This is answer 3"
},
"4":{
"answer":"This is question 4",
"question":"This is answer 4"
},
"5":{
"answer":"This is question 5",
"question":"This is answer 5"
}
};
final models = data.keys.map((key) {
final subData = data[key];
return FaqModel.fromJson(subData);
});
models.forEach((item) {
print("FAQ: ${item.question} \n ${item.answer}\n\n");
});
只需使用下面的模型
// To parse this JSON data, do
//
// final faqModel = faqModelFromJson(jsonString);
import 'dart:convert';
Map<String, FaqModel> faqModelFromJson(String str) => Map.from(json.decode(str)).map((k, v) => MapEntry<String, FaqModel>(k, FaqModel.fromJson(v)));
String faqModelToJson(Map<String, FaqModel> data) => json.encode(Map.from(data).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())));
class FaqModel {
String answer;
String question;
FaqModel({
this.answer,
this.question,
});
factory FaqModel.fromJson(Map<String, dynamic> json) => FaqModel(
answer: json["answer"] == null ? null : json["answer"],
question: json["question"] == null ? null : json["question"],
);
Map<String, dynamic> toJson() => {
"answer": answer == null ? null : answer,
"question": question == null ? null : question,
};
}
和解析JSON
FaqModel faqModel = faqModelFromJson(jsonData);
试试这个:
FaqModel faqModel = faqModelFromJson(jsonData);