how can i fetch nested json data - json

#I am able to fetch id name address but i am not able to fetch image which is src which is inside image need help
#This is my model class
class CategoryModel with ChangeNotifier{
CategoryModel({
this.id,
this.name,
this.slug,
this.parent,
this.description,
this.display,
this.image,
this.menuOrder,
this.count,
this.yoastHead,
this.yoastHeadJson,
this.links,
});
int? id;
String? name;
String? slug;
int? parent;
String? description;
String? display;
Image? image;
int? menuOrder;
int? count;
String? yoastHead;
YoastHeadJson? yoastHeadJson;
Links? links;
factory CategoryModel.fromJson(Map<String, dynamic> json) => CategoryModel(
id: json["id"],
name: json["name"],
slug: json["slug"],
parent: json["parent"],
description: json["description"],
display: json["display"],
image: json["image"] == null ? null : Image.fromJson(json["image"]),
menuOrder: json["menu_order"],
count: json["count"],
yoastHead: json["yoast_head"],
yoastHeadJson: YoastHeadJson.fromJson(json["yoast_head_json"]),
links: Links.fromJson(json["_links"]),
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"slug": slug,
"parent": parent,
"description": description,
"display": display,
"image": image == null ? null : image!.toJson(),
"menu_order": menuOrder,
"count": count,
"yoast_head": yoastHead,
"yoast_head_json": yoastHeadJson!.toJson(),
"_links": links!.toJson(),
};
}
class Image {
Image({
this.id,
this.dateCreated,
this.dateCreatedGmt,
this.dateModified,
this.dateModifiedGmt,
this.src,
this.name,
this.alt,
});
int? id;
DateTime? dateCreated;
DateTime? dateCreatedGmt;
DateTime? dateModified;
DateTime? dateModifiedGmt;
String? src;
String? name;
String? alt;
factory Image.fromJson(Map<String, dynamic> json) => Image(
id: json["id"],
dateCreated: DateTime.parse(json["date_created"]),
dateCreatedGmt: DateTime.parse(json["date_created_gmt"]),
dateModified: DateTime.parse(json["date_modified"]),
dateModifiedGmt: DateTime.parse(json["date_modified_gmt"]),
src: json["src"],
name: json["name"],
alt: json["alt"],
);
Map<String, dynamic> toJson() => {
"id": id,
"date_created": dateCreated!.toIso8601String(),
"date_created_gmt": dateCreatedGmt!.toIso8601String(),
"date_modified": dateModified!.toIso8601String(),
"date_modified_gmt": dateModifiedGmt!.toIso8601String(),
"src": src,
"name": name,
"alt": alt,
};
}
#This is how i try to fetch data. i am trying to fetch data and store that data in a list so that i can render that data according to my design
Future<void> fetchCategory(BuildContext context) async{
const url = "https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-json/wc/v3/products/categories";
try{
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
print(extractedData);
List<CategoryModel> loadedData = [];
if(extractedData == null){
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Data is Null failed to fetch data!"),
duration: Duration(seconds: 3),));
}
extractedData.forEach((element){
loadedData.add(CategoryModel(
id:element['id'],
name:element['name'],
image: element['image']['src']
// image: element!['image']
// image: element['image']==null?Text("no Image to show"):element['image']['src']
));
});
_cItems = loadedData;
print(_cItems);
notifyListeners();
}catch(e){
rethrow;
}
}
#But i am unable to fetch image Image is in nested data like this
[
{id: 25,
name: Bakery,
slug: bakery,
parent: 0,
description: ,
display: products,
image: {
id: 83,
date_created: 2021-07-16T12:16:24,
date_created_gmt: 2021-07-16T12:16:24,
date_modified: 2021-07-16T12:16:24,
date_modified_gmt: 2021-07-16T12:16:24,
src: https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-content/uploads/2021/07/Intersection.png,
name: Intersection,
alt:
}
]
#I wanna fetch the src inside Image

Shouldn't you use the fromJson method that you have declared in the CategoryModel?
*edit
Something like this:
loadedData.add(CategoryModel.fromJson(element));
**edit
How to filter data?
Future<void> fetchCategory(BuildContext context) async{
const url = "https://sweet-ardinghelli.3-108-138-206.plesk.page/wp-json/wc/v3/products/categories";
try{
final response = await http.get(Uri.parse(url));
final extractedData = json.decode(response.body);
print(extractedData);
List<CategoryModel> loadedData = [];
if(extractedData == null){
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Data is Null failed to fetch data!"),
duration: Duration(seconds: 3),));
}
extractedData.forEach((element){
// Something like this to filter the elements before adding to list.
final item = CategoryModel.fromJson(element);
if(item.on_sale == true){
loadedData.add(CategoryModel.fromJson(element));
}
});
_cItems = loadedData;
print(_cItems);
notifyListeners();
}catch(e){
rethrow;
}
}

Use https://app.quicktype.io/ to easily create model classes to parse from and to json.
And yes, it is available to dart and so many other languages.

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...

Flutter How to parse Api response?

Im working with rawg.io api and trying to get datas about games. There is a problem which i think it's about parsing data from json. I worked with easy apis which has not arrays or maps in it. But this data complicated and i guess that's why im getting always null results while try to print datas to screen.
Here is my code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:video_games/load_data.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Future<Welcome> apiCall() async {
final response = await http.get(Uri.parse(
'https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56'));
print(response.statusCode);
print(response.body);
return Welcome.fromJson(jsonDecode(response.body));
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: FutureBuilder<Welcome>(
future: apiCall(),
builder: (context, snapshot) {
// var growableList = [];
// List<Result> data = snapshot.data!.results;
// growableList.add(data[0].name);
return Text('${snapshot.data!.count}');
},
),
),
);
}
}
That is my response body and status code without using in a widget or parsing it
I/flutter ( 3666): 200
I/flutter ( 3666): {"count":679153,"next":"https://api.rawg.io/api/games?key=5ac29048d12d45d0949c77038115cb56&page=2","previous":null,"results":[{"id":3498,"slug":"grand-theft-auto-v","name":"Grand Theft Auto V","released":"2013-09-17","tba":false,"background_image":"https://media.rawg.io/media/games/456/456dea5e1c7e3cd07060c14e96612001.jpg","rating":4.48,"rating_top":5,"ratings":[{"id":5,"title":"exceptional","count":3217,"percent":58.97},{"id":4,"title":"recommended","count":1800,"percent":33.0},{"id":3,"title":"meh","count":348,"percent":6.38},{"id":1,"title":"skip","count":90,"percent":1.65}],"ratings_count":5389,"reviews_text_count":36,"added":16689,"added_by_status":{"yet":415,"owned":9874,"beaten":4491,"toplay":474,"dropped":835,"playing":600},"metacritic":97,"playtime":71,"suggestions_count":402,"updated":"2021-08-20T12:42:02","user_game":null,"reviews_count":5455,"saturated_color":"0f0f0f","dominant_color":"0f0f0f","platforms":[{"platform":{"id":1,"name":"Xbox One","slug":"xbox-one","image":null,"year_end":null,"year_
And this is my data class
// To parse this JSON data, do
//
// final welcome = welcomeFromJson(jsonString);
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
required this.count,
required this.next,
required this.previous,
required this.results,
});
int count;
String next;
String previous;
List<Result> results;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
count: json["count"],
next: json["next"],
previous: json["previous"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"count": count,
"next": next,
"previous": previous,
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
Result({
required this.id,
required this.slug,
required this.name,
required this.released,
required this.tba,
required this.backgroundImage,
required this.rating,
required this.ratingTop,
required this.ratings,
required this.ratingsCount,
required this.reviewsTextCount,
required this.added,
required this.addedByStatus,
required this.metacritic,
required this.playtime,
required this.suggestionsCount,
required this.updated,
required this.esrbRating,
required this.platforms,
});
int id;
String slug;
String name;
DateTime released;
bool tba;
String backgroundImage;
int rating;
int ratingTop;
AddedByStatus ratings;
int ratingsCount;
String reviewsTextCount;
int added;
AddedByStatus addedByStatus;
int metacritic;
int playtime;
int suggestionsCount;
DateTime updated;
EsrbRating esrbRating;
List<Platform> platforms;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
slug: json["slug"],
name: json["name"],
released: DateTime.parse(json["released"]),
tba: json["tba"],
backgroundImage: json["background_image"],
rating: json["rating"],
ratingTop: json["rating_top"],
ratings: AddedByStatus.fromJson(json["ratings"]),
ratingsCount: json["ratings_count"],
reviewsTextCount: json["reviews_text_count"],
added: json["added"],
addedByStatus: AddedByStatus.fromJson(json["added_by_status"]),
metacritic: json["metacritic"],
playtime: json["playtime"],
suggestionsCount: json["suggestions_count"],
updated: DateTime.parse(json["updated"]),
esrbRating: EsrbRating.fromJson(json["esrb_rating"]),
platforms: List<Platform>.from(
json["platforms"].map((x) => Platform.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"id": id,
"slug": slug,
"name": name,
"released":
"${released.year.toString().padLeft(4, '0')}-${released.month.toString().padLeft(2, '0')}-${released.day.toString().padLeft(2, '0')}",
"tba": tba,
"background_image": backgroundImage,
"rating": rating,
"rating_top": ratingTop,
"ratings": ratings.toJson(),
"ratings_count": ratingsCount,
"reviews_text_count": reviewsTextCount,
"added": added,
"added_by_status": addedByStatus.toJson(),
"metacritic": metacritic,
"playtime": playtime,
"suggestions_count": suggestionsCount,
"updated": updated.toIso8601String(),
"esrb_rating": esrbRating.toJson(),
"platforms": List<dynamic>.from(platforms.map((x) => x.toJson())),
};
}
class AddedByStatus {
AddedByStatus();
factory AddedByStatus.fromJson(Map<String, dynamic> json) => AddedByStatus();
Map<String, dynamic> toJson() => {};
}
class EsrbRating {
EsrbRating({
required this.id,
required this.slug,
required this.name,
});
int id;
String slug;
String name;
factory EsrbRating.fromJson(Map<String, dynamic> json) => EsrbRating(
id: json["id"],
slug: json["slug"],
name: json["name"],
);
Map<String, dynamic> toJson() => {
"id": id,
"slug": slug,
"name": name,
};
}
class Platform {
Platform({
required this.platform,
required this.releasedAt,
required this.requirements,
});
EsrbRating platform;
String releasedAt;
Requirements requirements;
factory Platform.fromJson(Map<String, dynamic> json) => Platform(
platform: EsrbRating.fromJson(json["platform"]),
releasedAt: json["released_at"],
requirements: Requirements.fromJson(json["requirements"]),
);
Map<String, dynamic> toJson() => {
"platform": platform.toJson(),
"released_at": releasedAt,
"requirements": requirements.toJson(),
};
}
class Requirements {
Requirements({
required this.minimum,
required this.recommended,
});
String minimum;
String recommended;
factory Requirements.fromJson(Map<String, dynamic> json) => Requirements(
minimum: json["minimum"],
recommended: json["recommended"],
);
Map<String, dynamic> toJson() => {
"minimum": minimum,
"recommended": recommended,
};
}
Things i tried;
tried to convert response body to string before parsing
tried to change my widget to asnyc
tried to simplify my data class (to avoid arrays)
My opinion after research,
return Welcome.fromJson(jsonDecode(response.body));
this part can't work correctly cause of json decode can't decode complex datas which is has arrays and maps.
I stuck at this point and struggling. There is no document that i can do it correctly. Please help me about this.

NoSuchMethodError : The method 'map' was called on null. Plz Provide the Solution

I am trying to parse data from a Rest API inside a Dart/Flutter application.
The JSON contains a field called data at the root, which contains a list of Words.
I want to get a List<ArticalList> from this JSON giving json["data"].map((x) => ArticalList.fromJson(x))
I already have the following code:
import 'dart:convert';
Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));
String welcomeToJson(Welcome data) => json.encode(data.toJson());
class Welcome {
Welcome({
required this.code,
required this.status,
required this.message,
required this.data,
});
final int code;
final String status;
final String message;
final List<ArticalList> data;
factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
code: json["code"] ?? 0,
status: json["status"] ?? '',
message: json["message"] ?? '',
data: List<ArticalList>.from(json["data"].map((x) => ArticalList.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"code": code,
"status": status,
"message": message,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class ArticalList {
ArticalList({
required this.id,
required this.title,
required this.detail,
required this.image,
});
int id;
String title;
String detail;
String image;
factory ArticalList.fromJson(Map<String, dynamic> json) => ArticalList(
id: json["id"] == null ? 0 : json["id"],
title: json["title"] == null ? '' : json["title"],
detail: json["detail"] == null ? '' : json["detail"],
image: json["image"] ?? 'http://eduteksolutions.in/images/logo.jpeg',
);
Map<String, dynamic> toJson() => {
"id": id == null ? null : id,
"title": title == null ? null : title,
"detail": detail == null ? null : detail,
"image": image,
};
}
I think your getting error at
data: List<ArticalList>.from(json["data"].map((x) => ArticalList.fromJson(x))),
I create a function with null safety which accept map and return object list
static List<ArticalList> toListFormMap({
Map? map,
}) {
if (map?.isEmpty ?? true) return [];
List<ArticalList> items = [];
map?.forEach((key, data) {
final ArticalList item = ArticalList.fromJson(data);
items.add(item);
});
return items;
}
and same method which convert map to Map
static Map toMapList(List<ArticalList>? items) {
Map map = {};
items?.forEach((element) {
map[element.id] = element.toJson();
});
return map;
}
for both case it handle null data error and also convert Object List to Map list and Map list to Object list.
I hope it will be helpful.

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.

flutter : nested json parsing list

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}');