Home > front end >  How to parse data in Flutter/ dart?
How to parse data in Flutter/ dart?

Time:10-23

I have a List that look like this:

"workinghours": [
    {
      "shop": 31,
      "weekday": "monday",
      "start_time": "05:25 AM",
      "end_time": "11:00 AM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "monday",
      "start_time": "01:10 PM",
      "end_time": "05:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "tuesday",
      "start_time": "12:00 PM",
      "end_time": "05:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "tuesday",
      "start_time": "05:00 PM",
      "end_time": "10:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "tuesday",
      "start_time": "04:00 AM",
      "end_time": "05:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "wednesday",
      "start_time": "03:00 AM",
      "end_time": "11:00 AM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "wednesday",
      "start_time": "01:00 PM",
      "end_time": "11:00 AM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "wednesday",
      "start_time": "07:00 PM",
      "end_time": "11:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "thursday",
      "start_time": "06:00 AM",
      "end_time": "11:00 AM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "thursday",
      "start_time": "01:00 PM",
      "end_time": "05:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "thursday",
      "start_time": "07:00 PM",
      "end_time": "11:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "saturday",
      "start_time": "05:00 AM",
      "end_time": "12:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "saturday",
      "start_time": "01:00 PM",
      "end_time": "11:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "sunday",
      "start_time": "05:00 AM",
      "end_time": "11:00 PM",
      "is_closed": false
    },
    {
      "shop": 31,
      "weekday": "sunday",
      "start_time": "02:10 PM",
      "end_time": "10:00 PM",
      "is_closed": false
    }
  ],

Its basically a list of weekdays and the time which the shop open and closes. I need to convert this list to the below json model:

{
  "work_time": [
    {
        "shop_id": 11,
        "week_day": "monday",
        "work_time": [
          {
            "id": 11,
            "startTime": "",
            "endTime": "",
            "isClosed": true
          }
        ]
    },
    {
        "shop_id": 12,
        "week_day": "tuesday",
        "work_time": [
          {
            "id": 12,
            "startTime": "",
            "endTime": "",
            "isClosed": true
          },
          {
            "id": 12,
            "startTime": "",
            "endTime": "",
            "isClosed": true
          }
        ]
    }
  ]
}

And the model class is

ShopWorkTimeModel shopWorkTimeModelFromJson(String str) => ShopWorkTimeModel.fromJson(json.decode(str));

String shopWorkTimeModelToJson(ShopWorkTimeModel data) => json.encode(data.toJson());

class ShopWorkTimeModel {
    ShopWorkTimeModel({
        this.workTime,
    });

    List<ShopWorkTimeModelWorkTime> workTime;

    factory ShopWorkTimeModel.fromJson(Map<String, dynamic> json) => ShopWorkTimeModel(
        workTime: List<ShopWorkTimeModelWorkTime>.from(json["work_time"].map((x) => ShopWorkTimeModelWorkTime.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "work_time": List<dynamic>.from(workTime.map((x) => x.toJson())),
    };
}

class ShopWorkTimeModelWorkTime {
    ShopWorkTimeModelWorkTime({
        this.workingHourId,
        this.weekDay,
        this.workTime,
    });

    int workingHourId;
    String weekDay;
    List<WorkTimeWorkTime> workTime;

    factory ShopWorkTimeModelWorkTime.fromJson(Map<String, dynamic> json) => ShopWorkTimeModelWorkTime(
        workingHourId: json["working_hour_id"],
        weekDay: json["week_day"],
        workTime: List<WorkTimeWorkTime>.from(json["work_time"].map((x) => WorkTimeWorkTime.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "working_hour_id": workingHourId,
        "week_day": weekDay,
        "work_time": List<dynamic>.from(workTime.map((x) => x.toJson())),
    };
}

class WorkTimeWorkTime {
    WorkTimeWorkTime({
        this.id,
        this.startTime,
        this.endTime,
        this.isClosed,
    });

    int id;
    String startTime;
    String endTime;
    bool isClosed;

    factory WorkTimeWorkTime.fromJson(Map<String, dynamic> json) => WorkTimeWorkTime(
        id: json["id"],
        startTime: json["startTime"],
        endTime: json["endTime"],
        isClosed: json["isClosed"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "startTime": startTime,
        "endTime": endTime,
        "isClosed": isClosed,
    };
}

How to parse the above json to this model class in dart. In the above json file the list contains weekdays more than one times, so i need to convert that by having one weekday and list all the working hours in a list below that weekdays as i mentioned in the above model class.

CodePudding user response:

You can call this from your service layer it might work :)

class dummy {
  List<WorkTime>? workTime;

  dummy({this.workTime});

  dummy.fromJson(Map<String, dynamic> json) {
    if (json['work_time'] != null) {
      workTime = <WorkTime>[];
      json['work_time'].forEach((v) {
        workTime!.add(new WorkTime.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.workTime != null) {
      data['work_time'] = this.workTime!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class WorkTime {
  int? workingHourId;
  String? weekDay;
  List<WorkTime>? workTime;

  WorkTime({this.workingHourId, this.weekDay, this.workTime});

  WorkTime.fromJson(Map<String, dynamic> json) {
    workingHourId = json['working_hour_id'];
    weekDay = json['week_day'];
    if (json['work_time'] != null) {
      workTime = <WorkTime>[];
      json['work_time'].forEach((v) {
        workTime!.add(new WorkTime.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['working_hour_id'] = this.workingHourId;
    data['week_day'] = this.weekDay;
    if (this.workTime != null) {
      data['work_time'] = this.workTime!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class WorkTime {
  int? id;
  String? startTime;
  String? endTime;
  bool? isClosed;

  WorkTime({this.id, this.startTime, this.endTime, this.isClosed});

  WorkTime.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    startTime = json['startTime'];
    endTime = json['endTime'];
    isClosed = json['isClosed'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['startTime'] = this.startTime;
    data['endTime'] = this.endTime;
    data['isClosed'] = this.isClosed;
    return data;
  }
}

CodePudding user response:

You don't need to convert your first json to second one, just follow these step:

First Change your model classes to these:

ShopWorkTimeModel shopWorkTimeModelFromJson(String str) =>
    ShopWorkTimeModel.fromJson(json.decode(str));

String shopWorkTimeModelToJson(ShopWorkTimeModel data) =>
    json.encode(data.toJson());

class ShopWorkTimeModel {
  ShopWorkTimeModel({
    required this.workTime,
  });

  List<ShopWorkTimeModelWorkTime> workTime;

  factory ShopWorkTimeModel.fromJson(Map<String, dynamic> json) =>
      ShopWorkTimeModel(
        workTime: List<ShopWorkTimeModelWorkTime>.from(json.entries
            .map((x) => ShopWorkTimeModelWorkTime.fromJson({x.key: x.value}))),
      );

  Map<String, dynamic> toJson() => {
        "work_time": List<dynamic>.from(workTime.map((x) => x.toJson())),
      };
}

class ShopWorkTimeModelWorkTime {
  ShopWorkTimeModelWorkTime({
    required this.workingHourId,
    required this.weekDay,
    required this.workTime,
  });

  int workingHourId;
  String weekDay;
  List<WorkTimeWorkTime> workTime;

  factory ShopWorkTimeModelWorkTime.fromJson(Map<String, dynamic> json) =>
      ShopWorkTimeModelWorkTime(
        workingHourId: (json.values.first as List).first['shop'],
        weekDay: json.keys.first,
        workTime: List<WorkTimeWorkTime>.from((json.values.first as List)
            .map((x) => WorkTimeWorkTime.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "working_hour_id": workingHourId,
        "week_day": weekDay,
        "work_time": List<dynamic>.from(workTime.map((x) => x.toJson())),
      };
}

class WorkTimeWorkTime {
  WorkTimeWorkTime({
    required this.id,
    required this.startTime,
    required this.endTime,
    required this.isClosed,
  });

  int id;
  String startTime;
  String endTime;
  bool isClosed;

  factory WorkTimeWorkTime.fromJson(Map<String, dynamic> json) =>
      WorkTimeWorkTime(
        id: json["shop"],
        startTime: json["start_time"],
        endTime: json["end_time"],
        isClosed: json["is_closed"],
      );

  Map<String, dynamic> toJson() => {
        "shop": id,
        "start_time": startTime,
        "end_time": endTime,
        "is_closed": isClosed,
      };
}

then assume your first json call jsonData1 and use collection to group the item in it like this:

var groupped = groupBy(
  jsonData1['workinghours'] as List,
  (data) => data != null ? (data as Map)['weekday'] as String : '',
);

now you can convert your first json to your model class like this:

var result = ShopWorkTimeModel.fromJson(groupped);
  • Related