how to parse dynamic complex json to dart object or model

Viewed 93
{
"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"
    ]
  }
}
}

So this is the JSON I need to parse into the dart model. The problem I am having with this structure is that map inside answers are all dynamic. Also, the number of the maps inside answers is not always the same. For example, the next JSON response can be.

{
 "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"
   ]
  }
 }
}

which is different from the first response. I need to make a dart model that parses both responses.

1 Answers

This is relatively easy to do by using a "sub-model" of Answers which would be stored within the assumed InterviewRequest model.

For example:

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);
  }
}

Related