Home > database >  Filtering nested JSON response in Flutter
Filtering nested JSON response in Flutter

Time:09-30

Hello I have a question regarding filtering of nested json response from an API. Suppose I have this sample JSON response from an API:

{
    "results": {
        "data": {
            "parentName": "Vic",
            "parentFamName": "Lo",
            "children": [
                {
                    "childName": "Mark",
                    "childCount": 2,
                    "grandChildren": [
                        {
                            "grandChildName": "Kent",
                            "grandChildAge": 4,
                            "isBoy": true,
                        },
                        {
                            "grandChildName": "Chris",
                            "grandChildAge": 8
                            "isBoy": true,
                        }]
                },
                {
                    "childName": "Kim",
                    "childCount": 3,
                    "grandChildren": [
                        {
                            "grandChildName": "Martin",
                            "grandChildAge": 6,
                            "isBoy": true,
                        },
                        {
                            "grandChildName": "Thesa",
                            "grandChildAge": 4
                            "isBoy": false,
                        },
                        {
                            "grandChildName": "Beck",
                            "grandChildAge": 2,
                            "isBoy": false,
                        }]
                }]
        }
    }
}

then ill be decoding the response by:

final jsonResponse = jsonDecode(jsonString.body);
final parentResponse = jsonResponse['results']['data'];

But before I display it in a ListView.builder, how do I filter the parenetResponse wherein it will only include "isBoy" = true? like the final data response to display would be:

{
    "results": {
        "data": {
            "parentName": "Vic",
            "parentFamName": "Lo",
            "children": [
                {
                    "childName": "Mark",
                    "childCount": 2,
                    "grandChildren": [
                        {
                            "grandChildName": "Kent",
                            "grandChildAge": 4,
                            "isBoy": true,
                        },
                        {
                            "grandChildName": "Chris",
                            "grandChildAge": 8
                            "isBoy": true,
                        }]
                },
                {
                    "childName": "Kim",
                    "childCount": 3,
                    "grandChildren": [
                        {
                            "grandChildName": "Martin",
                            "grandChildAge": 6,
                            "isBoy": true,
                        },
                        ]
                }]
        }
    }
}

Thank you for any help!

CodePudding user response:

First create model class to parse your json:

class ParentModel {
  final String parentName;
  final List<ChildrenModel> children;

  ParentModel({required this.parentName, required this.children});
  static ParentModel fromJson(Map<String, dynamic> json) {
    var children = json['children'] as List;
    return ParentModel(
        parentName: json['parentName'],
        children: children.map((e) => ChildrenModel.fromJson(e)).toList());
  }
}

class ChildrenModel {
  final int count;
  final String name;
  final List<GrandChildModel> grandChildren;

  ChildrenModel({
    required this.count,
    required this.name,
    required this.grandChildren,
  });
  static ChildrenModel fromJson(Map<String, dynamic> json) {
    var grandChildren = json["grandChildren"] as List;
    return ChildrenModel(
        count: json['childCount'],
        name: json['childName'],
        grandChildren:
            grandChildren.map((e) => GrandChildModel.fromJson(e)).toList());
  }
}

class GrandChildModel {
  final int age;
  final String name;
  final bool isBoy;

  GrandChildModel({required this.age, required this.name, required this.isBoy});
  static GrandChildModel fromJson(Map<String, dynamic> json) {
    return GrandChildModel(
        age: json['grandChildAge'],
        name: json['grandChildName'],
        isBoy: json['isBoy']);
  }
}

then use this to show the boy grandChildren:

class TestParent extends StatefulWidget {
  const TestParent({super.key});

  @override
  State<TestParent> createState() => _TestParentState();
}

class _TestParentState extends State<TestParent> {
  @override
  Widget build(BuildContext context) {
    final parentResponse = jsonResponse['results']!['data'];
    var parent = ParentModel.fromJson(parentResponse!);
    return Scaffold(
      appBar: AppBar(title: Text("Testing")),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: parent.children.length,
              itemBuilder: (context, index) {
                return ListView.builder(
                  shrinkWrap: true,
                  itemCount: parent.children[index].grandChildren.length,
                  itemBuilder: (context, i) {
                    var grandChild = parent.children[index].grandChildren[i];
                    if (grandChild.isBoy) {
                      return Text(grandChild.name);
                    } else {
                      return SizedBox();
                    }
                  },
                );
              },
            ),
          )
        ],
      ),
    );
  }
}

Note that here jsonResponse is your json;

result:

enter image description here

CodePudding user response:

Without making model classes you could simply modify the response like this:

parentResponse['children'] = parentResponse['children']
  .map((child) => child
    ..['grandChildren'] = child['grandChildren']
      .where((grandChild) => grandChild['isBoy'] as bool)
      .toList())
  .toList();
  • Related