Flutter Json Dynamic Key Using model class

This post learn to dynamic json parsing flutter using model class json_serializableble.

Here is the Example of Flutter Json Dynamic Key Using model class

Flutter Json Dynamic Key Using model class
import 'dart:convert';
import '../model/user_detail.dart';
import '../model/user_data_response.dart';

main() {
  String json = '''
  {
    "success": true,
    "data": {
        "ones": [{
                "id": "2",
                "username": "LM10002"
            },
            {
                "id": "6",
                "username": "LM10006"
            }
        ],
        "twos": [{
                "id": "3",
                "username": "LM10003"
            },
            {
                "id": "8",
                "username": "LM10008"
            }
        ],
        "threes": [{
            "id": "4",
            "username": "LM10004"
        }],
        "fours": [{
                "id": "5",
                "username": "LM10005"
            },
            {
                "id": "14",
                "username": "GT10014"
            }
        ]
    }
}
  ''';

  UserDataResponse dynamicJsonResponse = UserDataResponse.fromJson(jsonDecode(json));
  Iterable<List<UserDetail>> userDetailMap = dynamicJsonResponse.userDetail!.values;

  userDetailMap.forEach((userDetailIterable) {
    userDetailIterable.forEach((userDetail) {
      print(userDetail.id);
    });
  });
}
import 'package:json_annotation/json_annotation.dart';
import 'user_detail.dart';
part 'user_data_response.g.dart';

@JsonSerializable(includeIfNull: true)
class UserDataResponse {
  bool? success;

  @JsonKey(name: 'data')
  Map<dynamic, List<UserDetail>>? userDetail;

  UserDataResponse({this.success, this.userDetail});

  factory UserDataResponse.fromJson(Map<String, dynamic> json) =>
      _$UserDataResponseFromJson(json);
  Map<String, dynamic> toJson() => _$UserDataResponseToJson(this);
}
import 'package:json_annotation/json_annotation.dart';
part 'user_detail.g.dart';

@JsonSerializable(includeIfNull: true)
class UserDetail {
  String? id;

  UserDetail({this.id});

  factory UserDetail.fromJson(Map<String, dynamic> json) => _$UserDetailFromJson(json);
  Map<String, dynamic> toJson() => _$UserDetailToJson(this);
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in