flutter : nested json parsing list - json

I am trying to call Name and Fees from my json code
it is nested array from main array of my json the main array i can deal with it but the sub array i can't
"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
],
And I can't do that because of the error here when iam tring to call 'Name' and 'Fees'
type 'List<ExtraServices>' is not a subtype of type 'String'
and this is my class for mapping tour guide data to use it in list view
class TourGuide{
String id;
String name;
String email;
String password;
List<ExtraServices> extraService;
TourGuide({
this.id,
this.name,
this.email,
this.password,
this.extraService,
});
TourGuide.fromJson(Map<String, dynamic> json){
List<dynamic> extra = json['guideExtraServices'];
List<ExtraServices> extraList = extra.map((i) => ExtraServices.fromJson(i)).toList();
id = json['id'].toString();
name = json['displayName'];
email = json['email'];
password = json['password'];
extraService=extraList;
}
}
and this is a Extra Services class which tour guide class depend on to get the sub array
class ExtraServices{
String name;
double fees;
ExtraServices({
this.name,
this.fees
});
ExtraServices.fromJson(Map<String, dynamic> json){
name = json['Name'];
fees = json['Fees'].toDouble();
}
}
my provider method for decode json using for api
Future<dynamic> tourGuideList() async {
_isLoading = true;
notifyListeners();
print('Starting request');
http.Response response = await http.get(Environment.tourGuide,
headers: Environment.requestHeader);
print('Completed request');
print('respond data : ${response.body}');
Map<String, dynamic> res = json.decode(response.body);
var results;
if (res['code'] == 200) {
print('start load tourguide');
_tourGuide = [];
res['message'].forEach((v) {
_tourGuide.add(new TourGuide.fromJson(v));
});
results = true;
} else {
results =
FailedRequest(code: 400, message: res['error'], status: false);
}
_isLoading = false;
notifyListeners();
return results;
}
and I don't know why I have an error and I can't fix it

I think your json should be like this in total:
{"guideExtraServices": [
{
"Name": "Limousine",
"Fees": 100
},
{
"Name": "Bus",
"Fees": 10000
},
{
"Name": "Mini-Bus",
"Fees": 5000
}
]}
Try
// To parse this JSON data, do
//
// final tourGuide = tourGuideFromJson(jsonString);
import 'dart:convert';
TourGuide tourGuideFromJson(String str) => TourGuide.fromJson(json.decode(str));
String tourGuideToJson(TourGuide data) => json.encode(data.toJson());
class TourGuide {
List<GuideExtraService> guideExtraServices;
TourGuide({
this.guideExtraServices,
});
factory TourGuide.fromJson(Map<String, dynamic> json) => TourGuide(
guideExtraServices: List<GuideExtraService>.from(json["guideExtraServices"].map((x) => GuideExtraService.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"guideExtraServices": List<dynamic>.from(guideExtraServices.map((x) => x.toJson())),
};
}
class GuideExtraService {
String name;
int fees;
GuideExtraService({
this.name,
this.fees,
});
factory GuideExtraService.fromJson(Map<String, dynamic> json) => GuideExtraService(
name: json["Name"],
fees: json["Fees"],
);
Map<String, dynamic> toJson() => {
"Name": name,
"Fees": fees,
};
}

Please try the below code :-
First Create Model :-
class GuideResponseModel {
List<GuideExtraServicesModel> guideExtraServiceList;
GuideResponseModel({
this.guideExtraServiceList
});
factory GuideResponseModel.fromJson(Map<String, dynamic> parsedJson) {
try {
List<GuideExtraServicesModel> guideExtraServiceModelList = new List();
if (parsedJson.containsKey('guideExtraServices')) {
var countryList = parsedJson['guideExtraServices'] as List;
guideExtraServiceModelList =
countryList.map((i) => GuideExtraServicesModel.fromJson(i)).toList();
}
return GuideResponseModel(
guideExtraServiceList: guideExtraServiceModelList
);
} catch (e) {
return null;
}
}
}
class GuideExtraServicesModel {
String name;
int fees;
GuideExtraServicesModel({this.name,this.fees});
factory GuideExtraServicesModel.fromJson(Map<String, dynamic> json) {
return GuideExtraServicesModel(name: json['Name'],fees: json['Fees']);
}
}
Second User the Model:-
String jsonData = '{"guideExtraServices": [{"Name": "Limousine","Fees": 100},{"Name": "Bus","Fees": 10000},{"Name": "Mini-Bus","Fees": 5000}]}';
final dynamic jsonResponse = json.decode(jsonData);
final GuideResponseModel responseModel = GuideResponseModel.fromJson(jsonResponse);
print('======${responseModel.guideExtraServiceList[0].name}----${responseModel.guideExtraServiceList[0].fees}');

Related

Error To show Data Parsed Json In Flutter

I Have One Http Post Method Like This :
class ApiClientController extends GetxController {
Future<GetSideMenuInfoError?> GetInfoAfterLogin() async {
String? value = await storage.read(key: 'skey');
try {
final response = await dio.post(
Constant.baseUrl,
options: Options(
headers: {
"omax-apikey": "apikey",
},
),
data: {
"function": "portal_get_information",
"params": {
"portal_version": "1.0.0",
"portal_os": "linux",
"portal_os_version": "10",
"portal_browser": "chrome",
"portal_guid": "fd298776-6014-11ed-adbc-5256454165"
}
},
);
//print(response.data.toString());
GetSideMenuInfoError? responseBody = getSideMenuInfoErrorFromJson(response.data.toString());
return responseBody;
} on DioError catch (e) {
//return ;
print(e);
}
return null;
//IMPLEMENT USER LOGIN
}
}
And The Result Post Method My Json :
{
"result": 55456465,
"data": {
"reason": "session expired or not valid",
"uuid": "01dfca14-625559-11ed-aafa-0056546546"
}
}
Used This https://app.quicktype.io/ for Parsed Json To dart File Result Like This:
import 'package:meta/meta.dart';
import 'dart:convert';
GetSideMenuInfoError? getSideMenuInfoErrorFromJson(String str) => GetSideMenuInfoError?.fromJson(json.decode(str));
class GetSideMenuInfoError {
GetSideMenuInfoError({
#required this.result,
#required this.data,
});
final int? result;
final Data? data;
factory GetSideMenuInfoError.fromJson(Map<String, dynamic> json) => GetSideMenuInfoError(
result: json["result"],
data: Data.fromJson(json["data"]),
);
}
class Data {
Data({
#required this.reason,
#required this.uuid,
});
final String? reason;
final String? uuid;
factory Data.fromJson(Map<String, dynamic> json) => Data(
reason: json["reason"],
uuid: json["uuid"],
);
}
And My Question Is : How Can I Show value in Dart File Like reason or uuid In Other Class ?
My Way like This in Other Class And Not Worked:
In The Build Widget :
final apiClientController = Get.find<ApiClientController>();
apiClientController.GetInfoAfterLogin();
GetSideMenuInfoError? getSideMenuInfoError;
title: getSideMenuInfoError != null ?
Text(getSideMenuInfoError.result.toString()):Text('',),
Thank You For Helping Me...

How to get json response in flutter using POST method?

I am beginner in flutter. Please help me get and set below json data into model in flutter. I am using POST method.
'''
{
"success": 1,
"data": {
"user_id": 2,
"email": "ajay.singhal#ollosoft1.com",
"phone": "9414905280",
"password": "1436a615e62482ba4f075c1d4a4fd94b",
"account_status": "Active",
"date_of_birth": "1953-09-07T00:00:00.000Z",
"address": "Jaipur Rajasthan",
"profile_url": "http://18.217.236.99:4200/assets/profile_img/2/RBI-keeps-policy-rate-unchanged-1.jpg",
"first_name": "Ajay",
"last_name": "singhal"
}
}
'''
Below is my Model class named UserInfoModel
import 'UserInfoDataModel.dart';
class UserInfoModel {
final int success;
final UserInfoDataModel data;
UserInfoModel(this.success, this.data);
factory UserInfoModel.fromJson(dynamic json) {
if (json['data'] != null) {
var tagObjsJson = json['data'];
UserInfoDataModel _tags =
tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
return UserInfoModel(json['success'] as int, _tags);
}
}
#override
String toString() {
return '{${this.success}, ${this.data}}';
}
}
Below is submodel name is UserInfoDataModel
import 'package:flutter/material.dart';
class UserInfoDataModel {
int user_id;
String email;
String phone;
String password;
String account_status;
String date_of_birth;
String address;
String profile_url;
String first_name;
String last_name;
UserInfoDataModel(
{this.user_id,
this.email,
this.phone,
this.password,
this.account_status,
this.date_of_birth,
this.address,
this.profile_url,
this.first_name,
this.last_name});
factory UserInfoDataModel.fromJson(Map<String, dynamic> json) {
return UserInfoDataModel(
user_id: json['user_id'] as int,
email: json['email'],
phone: json['phone'],
password: json['password'],
account_status: json['account_status'],
date_of_birth: json['date_of_birth'],
address: json['address'],
profile_url: json['profile_url'],
first_name: json['first_name'],
last_name: json['last_name'],
);
}
}
My APi Call is below Using POST Method
I am successfully getting response, but unable to set in model
UserInfoModel _userInfoModel;
UserInfoDataModel _userInfoDataModel;
String url = BaseURLHeaders().getBaseURl() + "userInfo";
Map headers = BaseURLHeaders().getHeader();
#override
void initState() {
// TODO: implement initState
super.initState();
getData();
}
Future<UserInfoModel> getData() async {
String user_id = "1";
var mapData = new Map<String, dynamic>();
mapData['user_id'] = user_id;
// mapData['first_name'] = firstName;
var response = await http.post(
url,
headers: headers,
body: mapData,
);
setState(() {
print("userInfoDetails: ${response.body}");
print("urlTop: ${url}");
print("headersTop: ${headers}");
print("responseCode: ${response.statusCode}");
});
if (response.statusCode == 200) {
var res = json.decode(response.body);
_userInfoModel = UserInfoModel.fromJson(res);
if (_userInfoModel.success == 1) {
var data = res["data"];
setState(() {
print("responseBody: ${res}");
print("userInfoSuccess: ${_userInfoModel.success}");
print("dataVaalue: ${data["email"]}");
print("urlBelow: ${url}");
print("headersBelow: ${headers}");
});
}
}
}
UserInfoDataModel _tags =
tagObjsJson.map((tagJson) => UserInfoDataModel.fromJson(tagJson));
here you are actually treated tagObjsJson as a list. but it is a JsonObject so there you don't want the map function.
you can access the object as
UserInfoDataModel _tags =UserInfoDataModel.fromJson(tagJson);
You can use json_serializer in flutter. See flutter docs.
If you use IntelliJ IDEA, you can use DartToJson package. It generates automatically for you and you can use fromJson and toJson method.

How to parse a nested JSON dictionary (map)

I am trying to read a JSON code which is compatible with a Swift program into a flutter app. The structure is like this:
{
"tagDict" : {
"abc" : {
"helpHdr" : "short text1",
"helpText" : "long text1"
},
"def" : {
"helpHdr" : "short text2",
"helpText" : "long text2"
}
}
}
This creates in Swift a dictionary and shall create a map in Dart of the type {key : {helpHdr, helpText}}. A variable based on this should enable label = myVariable[tag].helpHdr, or staying with the example label = myVariable["abc"].helpHdr should assign "short text1" to label
To parse nested arrays I am using this, however, no clue how to transfer this to such a nested map.
class MyClass {
List<MySubClass> myArray;
MyClass({
this.myArray,
});
factory MyClass.fromJson(Map<String, dynamic> parsedJson){
var list = parsedJson['myArray'] as List;
List<MySubClass> listObject = list.map((i) => MySubClass.fromJson(i)).toList();
return new MyClass(
myArray: listObject,
);
}
}
class MySubClass {
int id;
String text1;
String text2;
MySubClass({
this.id,
this.text1,
this.text2,
});
factory MySubClass.fromJson(Map<String, dynamic> parsedJson){
return new MySubClass(
id: parsedJson['id'],
text1: parsedJson['text1'],
text2: parsedJson['text2'],
);
}
}
If I'm correct you want to parse your json into Data class object. If that's right then you can try this
void main() {
List<MyClass> myClassList = new List<MyClass>();
Map map = {
"tagDict": {
"abc": {"helpHdr": "short text1", "helpText": "long text1"},
"def": {"helpHdr": "short text2", "helpText": "long text2"}
}
};
map['tagDict'].forEach((key, value) {
value['id'] = key;
myClassList.add(MyClass.fromJson(value));
});
myClassList.forEach((myClass) {
print(myClass.id);
print(myClass.helpHdr);
print(myClass.helpText);
print("--------------------\n");
});
}
class MyClass {
String id;
String helpHdr;
String helpText;
MyClass({this.id, this.helpHdr, this.helpText});
MyClass.fromJson(Map<String, dynamic> json) {
id = json['id'];
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
This is the Output:
abc
short text1
long text1
--------------------
def
short text2
long text2
--------------------
class TagRes {
TagDict tagDict;
TagRes({this.tagDict});
TagRes.fromJson(Map<String, dynamic> json) {
tagDict =
json['tagDict'] != null ? new TagDict.fromJson(json['tagDict']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.tagDict != null) {
data['tagDict'] = this.tagDict.toJson();
}
return data;
}
}
class TagDict {
Abc abc;
Abc def;
TagDict({this.abc, this.def});
TagDict.fromJson(Map<String, dynamic> json) {
abc = json['abc'] != null ? new Abc.fromJson(json['abc']) : null;
def = json['def'] != null ? new Abc.fromJson(json['def']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.abc != null) {
data['abc'] = this.abc.toJson();
}
if (this.def != null) {
data['def'] = this.def.toJson();
}
return data;
}
}
class Abc {
String helpHdr;
String helpText;
Abc({this.helpHdr, this.helpText});
Abc.fromJson(Map<String, dynamic> json) {
helpHdr = json['helpHdr'];
helpText = json['helpText'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['helpHdr'] = this.helpHdr;
data['helpText'] = this.helpText;
return data;
}
}
Based on Tipu's answer, I came up with the following code which creates the intended dictionary (or map in Dart - why couldn't they stick to standard terminology like arrays etc?!)
class TaskTags {
var tagDict = Map<String, TaskTag>();
TaskTags({
this.tagDict,
});
factory TaskTags.fromJson(Map<String, dynamic> json){
var innerMap = json['tagDict'];
var tagMap = Map<String, TaskTag>();
innerMap.forEach((key, value) {
tagMap.addAll({key: TaskTag.fromJson(value)});
});
return new TaskTags(
tagDict: tagMap,
);
}
}
class TaskTag {
String helpHdr;
String helpText;
TaskTag({
this.helpHdr,
this.helpText,
});
factory TaskTag.fromJson(Map<String, dynamic> json){
return new TaskTag(
helpHdr: json['helpHdr'],
helpText: json['helpText'],
);
}
}
This creates the following map
{"abc“ : {helpHdr: "short text1", helpText: "long text1"}, "def“ : {helpHdr: "short text2", helpText: "long text2"}}

cannot resolve type 'String' is not a subtype of type 'int' of 'index'

i started having an issue recently. I need to parse my json response to a list to my model object class but i keep getting this error:
type 'String' is not a subtype of type 'int' of 'index'
tried several solutions online but it didn't work for me. I was thing my variable declarations in my model class was the issue so i changed them to dynamic but didnt still work for me.
Heading
Model
class MenteeIndex {
dynamic id;
dynamic mentor_id;
dynamic mentee_id;
dynamic status;
dynamic session_count;
dynamic current_job;
dynamic email;
dynamic phone_call;
dynamic video_call;
dynamic face_to_face;
dynamic created_at;
dynamic updated_at;
MenteeIndex(this.id, this.mentor_id, this.mentee_id, this.status, this.session_count, this.current_job,
this.email, this.phone_call, this.video_call, this.face_to_face, this.created_at, this.updated_at);
Map<String, dynamic> toJson() => {
'id': id,
'mentor_id': mentor_id,
'mentee_id': mentee_id,
'status': status,
'session_count': session_count,
'current_job': current_job,
'email':email,
'phone_call': phone_call,
'video_call': video_call,
'face_to_face': face_to_face,
'created_at': created_at,
'updated_at': updated_at,
};
MenteeIndex.fromJson(Map<String, dynamic> json):
id = json['id'],
mentor_id = json['mentor_id'],
mentee_id = json['mentee_id'],
status = json['status'],
session_count = json['session_count'],
current_job = json['current_job'],
email = json['email'],
phone_call = json['phone_call'],
video_call = json['video_call'],
face_to_face = json['face_to_face'],
created_at = json['created_at'],
updated_at = json['updated_at'];
}
Main
Future fetchIndex() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host + AuthUtils.endPointIndex;
try {
final response = await http.get(
uri,
headers: {'Accept': 'application/json', 'Content-Type': 'application/json','Authorization': 'Bearer ' + sharedPreferences.get("token"), },
);
var encodeFirst = json.encode(response.body);
final responseJson = json.decode(encodeFirst);
//here is where the error is
for (var u in responseJson["data"]) {
MenteeIndex user = MenteeIndex(
u["id"],
u["mentor_id"],
u["mentee_id"],
u["status"],
u["session_count"],
u["current_job"],
u["email"],
u["phone_call"],
u["video_call"],
u["face_to_face"],
u["created_at"],
u["updated_at"]);
menteeIndexes.add(user);
setState((){
mentorIdList = menteeIndexes.map((MenteeIndex) => MenteeIndex.mentor_id);
indexIds = menteeIndexes.map((MenteeIndex) => MenteeIndex.id);
status = menteeIndexes.map((MenteeIndex) => MenteeIndex.status);
});
}
return responseJson;
} catch (exception) {
print(exception);
}
}
Response/Error
{"current_page":1,"data":[{"id":13,"mentor_id":"5","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-20 20:37:50","updated_at":"2020-02-20 20:37:50"},{"id":14,"mentor_id":"8","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-21 22:39:31","updated_at":"2020-02-21 22:39:31"},{"id":15,"mentor_id":"10","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:15:23","updated_at":"2020-02-23 05:15:23"},{"id":16,"mentor_id":"191","mentee_id":"184","status":null,"session_count":0,"current_job":null,"email":null,"phone_call":null,"video_call":null,"face_to_face":null,"created_at":"2020-02-23 05:17:34","updated_at":"2020-02-23 05:17:34"},{"id":17,"mentor_id":"141","mentee_id":"184","status":"1",
I/flutter (20995): type 'String' is not a subtype of type 'int' of 'index'
Decode the response body to Map
final responseJson = json.decode(response.body);
Convert the Map list to MenteeIndex list
final menteeIndexes = responseJson["data"].map(
(json) => MenteeIndex.fromJson(json)
).toList();
Check out this model class
// To parse this JSON data, do
//
// final yourModel = yourModelFromJson(jsonString);
import 'dart:convert';
YourModel yourModelFromJson(String str) => YourModel.fromJson(json.decode(str));
String yourModelToJson(YourModel data) => json.encode(data.toJson());
class YourModel {
int currentPage;
List<Datum> data;
YourModel({
this.currentPage,
this.data,
});
factory YourModel.fromJson(Map<String, dynamic> json) => YourModel(
currentPage: json["current_page"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"current_page": currentPage,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
int id;
String mentorId;
String menteeId;
dynamic status;
int sessionCount;
dynamic currentJob;
dynamic email;
dynamic phoneCall;
dynamic videoCall;
dynamic faceToFace;
DateTime createdAt;
DateTime updatedAt;
Datum({
this.id,
this.mentorId,
this.menteeId,
this.status,
this.sessionCount,
this.currentJob,
this.email,
this.phoneCall,
this.videoCall,
this.faceToFace,
this.createdAt,
this.updatedAt,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
id: json["id"],
mentorId: json["mentor_id"],
menteeId: json["mentee_id"],
status: json["status"],
sessionCount: json["session_count"],
currentJob: json["current_job"],
email: json["email"],
phoneCall: json["phone_call"],
videoCall: json["video_call"],
faceToFace: json["face_to_face"],
createdAt: DateTime.parse(json["created_at"]),
updatedAt: DateTime.parse(json["updated_at"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"mentor_id": mentorId,
"mentee_id": menteeId,
"status": status,
"session_count": sessionCount,
"current_job": currentJob,
"email": email,
"phone_call": phoneCall,
"video_call": videoCall,
"face_to_face": faceToFace,
"created_at": createdAt.toIso8601String(),
"updated_at": updatedAt.toIso8601String(),
};
}
Just insert you response.body to this method :
final yourModel = yourModelFromJson(response.body);
you can just get the list of data using below call :
List<Datum> dataList = List();
dataList = yourModel.data;
here you get the list of data
You will get your Single object from it and then depending on that you can do what ever you want.

get value from nested json array and check if it is empty or not in flutter

My json array looks like:
[
{
"sub_categories": [],
"category_id": "82",
"catgory_name": "Andrew Murray 1 Month",
"parent_cat_id": "1"
},
{
"sub_categories": [
{
"category_id": "177",
"catgory_name": "2 Samuel",
"parent_cat_id": "167"
}
],
"category_id": "167",
"catgory_name": "The Bible ASV",
"parent_cat_id": "1"
},
]
First i want to display "catgory_name" in listview and if that catgory_name has sub_categories array than i need to display it in another list , so how can i achieve this.
i get all catgory_name by following code:
class CategoryModel {
final String name;
final List<SubCategoryModel> SubCategory;
CategoryModel({
this.name,
this.SubCategory,
});
factory CategoryModel.fromJson(Map<String, dynamic> json) {
return new CategoryModel(
name: json['catgory_name'].toString(),
SubCategory: parsesub_categories(json['sub_categories']),
// SubCategory:(json['sub_categories'] as List).map((map) => map).toList(),
);
}
static List<SubCategoryModel> parsesub_categories(cateJson) {
List<SubCategoryModel> catlist = new List<SubCategoryModel>.from(cateJson);
return catlist;
}
but sub_categories i could not get that array .
You can create data model as below:
class CategoryModel {
List<SubCateogryModel> subCategories;
String categoryId;
String catgoryName;
String parentCatId;
CategoryModel(
{this.subCategories,
this.categoryId,
this.catgoryName,
this.parentCatId});
CategoryModel.fromJson(Map<String, dynamic> json) {
if (json['sub_categories'] != null) {
subCategories = new List<SubCateogryModel>();
json['sub_categories'].forEach((v) {
subCategories.add(new SubCateogryModel.fromJson(v));
});
}
categoryId = json['category_id'];
catgoryName = json['catgory_name'];
parentCatId = json['parent_cat_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.subCategories != null) {
data['sub_categories'] =
this.subCategories.map((v) => v.toJson()).toList();
}
data['category_id'] = this.categoryId;
data['catgory_name'] = this.catgoryName;
data['parent_cat_id'] = this.parentCatId;
return data;
}
}
class SubCateogryModel {
String categoryId;
String catgoryName;
String parentCatId;
SubCateogryModel({this.categoryId, this.catgoryName, this.parentCatId});
SubCateogryModel.fromJson(Map<String, dynamic> json) {
categoryId = json['category_id'];
catgoryName = json['catgory_name'];
parentCatId = json['parent_cat_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['category_id'] = this.categoryId;
data['catgory_name'] = this.catgoryName;
data['parent_cat_id'] = this.parentCatId;
return data;
}
}
Now, you have to parse your json array into Data model array
List<CategoryModel> categoryList = [];
jsonArray.forEach((val){
categoryList.add(CategoryModel.fromJson(val));
});
Now, the UI code,
ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text(categoryList[index].catgoryName),
subtitle: categoryList[index].subCategories.isNotEmpty
? Column(
children: List.generate(
categoryList[index].subCategories.length, (position) {
String subCategory = categoryList[index]
.subCategories[position]
.catgoryName;
return Text(subCategory);
}),
)
: SizedBox(),
);
},
itemCount: categoryList.length,
)
You can use QuickType.io to generate dart classes (PODOs) for json.
import 'dart:convert';
List<CategoryModel> categoryModelFromJson(String str) => List<CategoryModel>.from(json.decode(str).map((x) => CategoryModel.fromJson(x)));
String categoryModelToJson(List<CategoryModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class CategoryModel {
List<CategoryModel> subCategories;
String categoryId;
String catgoryName;
String parentCatId;
CategoryModel({
this.subCategories,
this.categoryId,
this.catgoryName,
this.parentCatId,
});
factory CategoryModel.fromJson(Map<String, dynamic> json) => CategoryModel(
subCategories: json["sub_categories"] == null ? null : List<CategoryModel>.from(json["sub_categories"].map((x) => CategoryModel.fromJson(x))),
categoryId: json["category_id"],
catgoryName: json["catgory_name"],
parentCatId: json["parent_cat_id"],
);
Map<String, dynamic> toJson() => {
"sub_categories": subCategories == null ? null : List<dynamic>.from(subCategories.map((x) => x.toJson())),
"category_id": categoryId,
"catgory_name": catgoryName,
"parent_cat_id": parentCatId,
};
}