如何将动态复合体 json 解析为飞镖对象或模型

how to parse dynamic complex json to dart object or model

{
"transactionId": "11f8ecc05273e35a4eb2dc1a",
"type": "REQUEST_FOR_HH_INTERVIEW",
"answers": {
  "selectProvinceDistrictCommuneVillage": {
    "value": "01020706"
  },
  "positionOfOfficial": {
    "value": "Province Officer"
  },
  "enterKhmerName": {
    "value": "សុខ"
  },
  "selectSex": {
    "value": "MALE"
  },
  "dob": {
    "value": "1994-06-15T03:27:47.409Z"
  },
  "areYouMarried": {
    "value": "YES"
  },
  "scanSpousesID": {
    "value": "435465"
  },
  "enterSpousesKhmerName": {
    "value": "នារី"
  },
  "selectSexSpouse": {
    "value": "FEMALE"
  },
  "dobSpouse": {
    "value": "1996-08-15T03:27:47.409"
  },
  "numberOfMales": {
    "value": "4"
  },
  "numberOfFemales": {
    "value": "5"
  },
  "selectReasonForRequesting": {
    "value": [
      "NATURAL_DISASTER"
    ]
  }
}
}

这就是我需要解析到飞镖模型中的 JSON。我在这个结构中遇到的问题是答案中的地图都是动态的。此外,答案中的地图数量并不总是相同的。例如,下一个 JSON 响应可以是。

{
 "transactionId": "11f8ecc05273e35a4eb2dc1a",
 "type": "REQUEST_FOR_HH_INTERVIEW",
 "answers": {
   "selectCode": {
   "value": "01020706"
  },
  "selectRoomValue": {
  "value": "1996-08-15T03:27:47.409"
 },
 "numberOfFamilyMembers": {
  "value": "4"
  },
 "selectFoods": {
   "value": [
     "Piza",
     "Burger"
   ]
  }
 }
}

这与第一个响应不同。我需要制作一个解析两个响应的飞镖模型。

使用 Answers 的“sub-model”相对容易做到这一点,它会存储在假设的 InterviewRequest 模型中。

例如:

class InterviewRequest {
  final Answers answers;
  final String transactionId;

  factory InterviewRequest.fromJson(Map<String, dynamic> json) {
    return InterviewRequest(
      answers: Answers.fromJson(json['answers']),
      transactionId: json['transactionId'] as String,
    );
  }
}

class Answers {
  final List<Answer> answers;

  factory Answers.fromJson(Map<String, dynamic> json) {
    List answers = [];
    for (String question in json.keys)
      answers.add(Answer(question, json[key]));
    return Answers(answers);
  }
}