Home > database >  generate a list from Json parsed object
generate a list from Json parsed object

Time:12-01

I have a Json file like below and already parsed and Model passed to next page. What I am trying to generate a list based on YoutubeId on the next page.

final videoID;
final CourseLessonDetailsData courseLessons;
final CourseLessonsModel courseLessonsModel;

Json response:

{
    "CourseLessonDetailsData": [
        {
            "request_status": "Successful",
            "ID": "24973",
            "LessonContentDetails": [
                {
                    "TopicInfo": [
                        {
                            "ID": "2764",
                            "CourseCode": "DTS",
                        }
                    ],
                    "PreAssessment": [],
                    "Video": [
                        {
                            "YoutubeId": "yt_id1",
                        }
                    ],
                }
            ],
                }
                        {
            "request_status": "Successful",
            "ID": "24974",
            "LessonContentDetails": [
                {
                    "TopicInfo": [
                        {
                            "ID": "2765",
                            "CourseCode": "DTS",
                        }
                    ],
                    "PreAssessment": [],
                    "Video": [
                        {
                            "YoutubeId": "yt_id2",
                        }
                    ],
                }
            ],
                }
                        {
            "request_status": "Successful",
            "ID": "24975",
            "LessonContentDetails": [
                {
                    "TopicInfo": [
                        {
                            "ID": "2766",
                            "CourseCode": "DTS",
                        }
                    ],
                    "PreAssessment": [],
                    "Video": [
                        {
                            "YoutubeId": "yt_id3",
                        }
                    ],
                }
            ],
                }
            ]
        },

Using the following code, I'm able to parse the first item but not able to get the rest.

for(var data in widget.courseLessonsModel.courseLessonDetailsData as Iterable){
  youTubeIds.add(widget.courseLessons.lessonContentDetails!.first.video!.first.youtubeId);
}
print(youTubeIds);

Here's how to my list is printed.

[yt_id1, yt_id1, yt_id1]

while my expected output is

[yt_id1, yt_id2, yt_id3]

I'm aware that I'm using first so only the first option will be retrieved. How should I retrieve all and what to replace with first?

CodePudding user response:

try create a model for the items you had e.g.

import 'dart:convert';

Model modelFromJson(String str) => Model.fromJson(json.decode(str));

String modelToJson(Model data) => json.encode(data.toJson());

class Model {
    Model({
        this.requestStatus,
        this.id,
        this.lessonContentDetails,
    });

    String? requestStatus;
    String? id;
    List<LessonContentDetail>? lessonContentDetails;

    factory Model.fromJson(Map<String, dynamic> json) => Model(
        requestStatus: json["request_status"] == null ? null : json["request_status"]!,
        id: json["ID"] == null ? null : json["ID"]!,
        lessonContentDetails: json["LessonContentDetails"] == null ? null : List<LessonContentDetail>.from(json["LessonContentDetails"].map((x) => LessonContentDetail.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "request_status": requestStatus == null ? null : requestStatus!,
        "ID": id == null ? null : id!,
        "LessonContentDetails": lessonContentDetails == null ? null : List<dynamic>.from(lessonContentDetails!.map((x) => x.toJson())),
    };
}

class LessonContentDetail {
    LessonContentDetail({
        this.topicInfo,
        this.preAssessment,
        this.video,
    });

    List<TopicInfo>? topicInfo;
    List<dynamic>? preAssessment;
    List<Video>? video;

    factory LessonContentDetail.fromJson(Map<String, dynamic> json) => LessonContentDetail(
        topicInfo: json["TopicInfo"] == null ? null : List<TopicInfo>.from(json["TopicInfo"].map((x) => TopicInfo.fromJson(x))),
        preAssessment: json["PreAssessment"] == null ? null : List<dynamic>.from(json["PreAssessment"].map((x) => x)),
        video: json["Video"] == null ? null : List<Video>.from(json["Video"].map((x) => Video.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "TopicInfo": topicInfo == null ? null : List<dynamic>.from(topicInfo!.map((x) => x.toJson())),
        "PreAssessment": preAssessment == null ? null : List<dynamic>.from(preAssessment!.map((x) => x)),
        "Video": video == null ? null : List<dynamic>.from(video!.map((x) => x.toJson())),
    };
}

class TopicInfo {
    TopicInfo({
        this.id,
        this.courseCode,
    });

    String? id;
    String? courseCode;

    factory TopicInfo.fromJson(Map<String, dynamic> json) => TopicInfo(
        id: json["ID"] == null ? null : json["ID"]!,
        courseCode: json["CourseCode"] == null ? null : json["CourseCode"]!,
    );

    Map<String, dynamic> toJson() => {
        "ID": id == null ? null : id!,
        "CourseCode": courseCode == null ? null : courseCode!,
    };
}

class Video {
    Video({
        this.youtubeId,
    });

    String? youtubeId;

    factory Video.fromJson(Map<String, dynamic> json) => Video(
        youtubeId: json["YoutubeId"] == null ? null : json["YoutubeId"]!,
    );

    Map<String, dynamic> toJson() => {
        "YoutubeId": youtubeId == null ? null : youtubeId!,
    };
}

this model will hold the items you had from json but first assign them

as for the data you've given sample

 final dataList = {
    "CourseLessonDetailsData": [
      {
        "request_status": "Successful",
        "ID": "24973",
        "LessonContentDetails": [
          {
            "TopicInfo": [
              {"ID": "2764", "CourseCode": "DTS"}
            ],
            "PreAssessment": [],
            "Video": [
              {"YoutubeId": "yt_id1"}
            ]
          }
        ]
      },
      {
        "request_status": "Successful",
        "ID": "24973",
        "LessonContentDetails": [
          {
            "TopicInfo": [
              {"ID": "2764", "CourseCode": "DTS"}
            ],
            "PreAssessment": [],
            "Video": [
              {"YoutubeId": "yt_id2"}
            ]
          }
        ]
      },
      {
        "request_status": "Successful",
        "ID": "24973",
        "LessonContentDetails": [
          {
            "TopicInfo": [
              {"ID": "2764", "CourseCode": "DTS"}
            ],
            "PreAssessment": [],
            "Video": [
              {"YoutubeId": "yt_id3"}
            ]
          }
        ]
      }
    ]
  };
/// This the the model which gonna hold the data
final List<Model> models = [];
/// Now lets create a another list to put the id
final List<String> ids = [];

    runthisinOninit(){
    
       try {
    models.addAll(dataList["CourseLessonDetailsData"]!
        .map((e) => Model.fromJson(e))
        .toList());
  } finally {
    for (var x in models) {
      final xy = x.lessonContentDetails!;

      if (xy.isNotEmpty) {
        for (var y in xy) {
          final xyz = y.video!;
          for (var z in xyz) {
            ids.add(z.youtubeId!);
          }
        }
      }
    }

    log(ids.toList().toString(),name:"My ID LIST");
  }

}

////as per result will be 
////[yt_id1, yt_id2, yt_id3]

also you can try this from dart pad and copy this code from gist

https://gist.github.com/Erchil66/47777fd92e9c3f194a3cd81b5d49111a

CodePudding user response:

As mentioned in the question, I was trying to create a list from the Json model. I achieved this by creating an empty list first then add elements in it when I created my ListView.builder.

List ytIdList = [];
ListView.builder(
                itemCount: snapshot.data!.courseLessonDetailsData!.length,
                  itemBuilder: (context, index){
                  ytIdList.add(snapshot.data!.courseLessonDetailsData![index].lessonContentDetails!.first.video!.first.youtubeId);
                  // print(ytIdList);
                  return Card();
})

Then I passed this list to next page using the Navigator.

However, this is a terrible way to do this as I'm already passing the whole parsed object to the next page and it should be done on the next page instead of passing the list from the previous page.

  • Related